Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function pointer in Ruby?

Tags:

ruby

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!

like image 387
aaron Avatar asked Nov 11 '11 15:11

aaron


1 Answers

"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)
like image 118
Marc-André Lafortune Avatar answered Nov 10 '22 07:11

Marc-André Lafortune