Ruby中的函数指针?

aar*_*ron 9 ruby

也许这是一个愚蠢的问题,但我是红宝石的新手,我用Google搜索,发现这些:

proc=Proc.new {|x| deal_with(x)}
a_lambda = lambda {|a| puts a}
Run Code Online (Sandbox Code Playgroud)

但我想要这个:

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)
Run Code Online (Sandbox Code Playgroud)

但它给了我一个错误.我不知道如何在Ruby中做到这一点,任何人都可以提供帮助?非常感谢!

Mar*_*une 21

Ruby中很少使用"函数指针".在这种情况下,您通常会使用a Symbol#send不是:

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)
Run Code Online (Sandbox Code Playgroud)

如果你真的需要一个可调用的对象(例如,如果你想lambda/proc特别使用内联的情况),你可以使用#method:

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)
Run Code Online (Sandbox Code Playgroud)

  • @Romain:就像"函数指针"听起来那样非正式,我们可以将它理解为"如何在不实际调用它的情况下将函数(块/方法)存储在变量中".在Ruby中,这不是一件容易的事,因为块是第一类对象,但方法不是(你需要`obj.method(name)`来将它作为一个块) (4认同)
  • 可以提到红宝石中没有"函数指针"这样的东西.它基本上没用(就像在大多数动态语言中一样). (2认同)