Maybe it is a stupid question, but i'm new to ruby, and I googled it, found these:
proc=Proc.new {|x| deal_with(x)}
a_lambda = lambda {|a| puts a}
But I want this:
def forward_slash_to_back(string)
...
def back_slash_to_forward(string)
...
def add_back_slash_for_post(string)
...
...
case conversion_type
when /bf/i then proc=&back_slash_to_forward
when /fb/i then proc=&forward_slash_to_back
when /ad/i then proc=&add_back_slash_for_post
else proc=&add_back_slash_for_post
end
n_data=proc.call(c_data)
But it gives me an error. I don't know how to do that in Ruby, anyone can help? thanks a lot!
"Function pointers" are rarely used in Ruby. In this case, you would normally use a Symbol
and #send
instead:
method = case conversion_type
when /bf/i then :back_slash_to_forward
when /fb/i then :forward_slash_to_back
when /ad/i then :add_back_slash_for_post
else :add_back_slash_for_post
end
n_data = send(method, c_data)
If you really need a callable object (e.g. if you want to use an inline lambda/proc
for a case in particular), you can use #method
though:
m = case conversion_type
when /bf/i then method(:back_slash_to_forward)
when /fb/i then method(:forward_slash_to_back)
when /ad/i then ->(data){ do_something_with(data) }
else Proc.new{ "Unknown conversion #{conversion_type}" }
end
n_data = m.call(c_data)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With