Ruby 中的函数指针? [英] Function pointer in Ruby?

查看:31
本文介绍了Ruby 中的函数指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许这是一个愚蠢的问题,但我是 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}

但我想要这个:

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 中做到这一点,有人可以帮忙吗?非常感谢!

But it gives me an error. I don't know how to do that in Ruby, anyone can help? thanks a lot!

推荐答案

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

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

如果您确实需要一个可调用对象(例如,如果您想对特定情况使用内联 lambda/proc),则可以使用 #method:

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)

这篇关于Ruby 中的函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆