也许这是一个愚蠢的问题,但我是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中很少使用“函数指针”.在这种情况下,通常会使用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)
原文地址:https://www.jb51.cc/ruby/266088.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。