Ruby中的函数指针?

Ruby中的函数指针?,ruby,Ruby,也许这是个愚蠢的问题,但我对ruby还不熟悉,我在谷歌上搜索了一下,发现了以下几点: proc=Proc.new {|x| deal_with(x)} a_lambda = lambda {|a| puts a} 但我想要这个: def forward_slash_to_back(string) ... def back_slash_to_forward(string) ... def add_back_slash_for_post(string) ... ... case conversio

也许这是个愚蠢的问题,但我对ruby还不熟悉,我在谷歌上搜索了一下,发现了以下几点:

proc=Proc.new {|x| deal_with(x)}
a_lambda = lambda {|a| puts a}
但我想要这个:

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)
但这给了我一个错误。我不知道用Ruby怎么做,有人能帮忙吗? 非常感谢

“函数指针”在Ruby中很少使用。在这种情况下,通常使用
符号
#发送

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)
如果您确实需要一个可调用对象(例如,如果您想在特定情况下使用内联
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)

可以提到,ruby中没有“函数指针”这样的东西。而且它基本上是无用的(就像在大多数动态语言中一样)。@Romain:正如“函数指针”听起来很非正式一样,我们可以理解为“如何在不实际调用函数的情况下将函数(块/方法)存储在变量中”。在Ruby中,这并不简单,因为块是一级对象,而方法不是(你需要
obj.method(name)
将其作为一个块)Marc André:我看不出第二个例子的必要性,因为你会在最后编写
method(m)
,并且在
案例中只使用符号。还请注意,第一个
案例
将“method”方法与一个变量“method”进行了阴影处理,这可能会混淆OP(我在写它时被弄糊涂了:-p)@tokland:同意。我对第二个例子进行了编辑,使其更有意义。@Marc André:事实上,如果案例返回来自异构源的块,那么它确实有意义。出于好奇,你想解决什么问题?你怎么会需要跳过所有这些障碍?还是只是学术上的?