Function pointer in Ruby?

前端 未结 1 1102
南方客
南方客 2021-02-20 06:17

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}
1条回答
  •  温柔的废话
    2021-02-20 06:45

    "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)
    

    0 讨论(0)
提交回复
热议问题