加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby中的函数指针?

发布时间:2020-12-17 01:20:54 所属栏目:百科 来源:网络整理
导读:也许这是一个愚蠢的问题,但我是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
也许这是一个愚蠢的问题,但我是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中很少使用“函数指针”.在这种情况下,通常会使用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)

如果你真的需要一个可调用的对象(例如,如果你想特别使用一个内联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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读