【问题标题】:How to pass multiple function as argument in Ruby?如何在Ruby中传递多个函数作为参数?
【发布时间】:2015-09-15 23:21:58
【问题描述】:

我有三个函数ABC。我需要将AB 传递给C。我该怎么做?

def A a
end

def B b
end

def C( &f1, &f2 ) #  syntax error, unexpected ',', expecting ')'
  f1.call 123
  f2.call 234
end

def C( f1, f2 ) # this one ok
  f1.call 123
  f2.call 234
end

C( &A, &B) # syntax error, unexpected ',', expecting ')'

【问题讨论】:

  • 不,它不是,但它有一个很好的提示..
  • 你可以使用Object#public_send 例如def c(f1,f2); public_send(f1,123);public_send(f2,234);end; 和所有 c(:a, :b) 但需要此功能的原因是什么,您确定没有更好的解决方案吗? ruby 中也只有常量大写;方法定义应该是更低的snake_cased。
  • @engineersmnky 这足以成为一个答案。正是我推荐的,尤其是命名部分。

标签: ruby parameter-passing


【解决方案1】:

我建议使用Object#public_send 来执行此操作,尽管我认为如果您要更清楚地定义它,可能有更好的方法来处理您的情况。

同样,只有常量应该大写,方法应该以小写蛇形式定义。

例子:

#puts used for clarification purposes
class SomeClass
  def a(val)
    puts "method a called with #{val}"
  end
  def b(val)
    puts "method b called with #{val}"
  end
  def c (f1,f2)
   public_send(f1,123)
   public_send(f2,234)
  end
end

用法

s = SomeClass.new
s.c(:a,:b)
#method a called with 123
#method b called with 234
#=> nil

希望这对您有所帮助,就像我说的那样,如果您更清楚地定义用例,可能并且很可能有更好的方法来处理问题。

注意:上面的代码在输入 irb 时不能直接在 main:Object 的上下文中工作。相反,它会通知您为main:Object 调用了一个私有方法。这是因为在 irb 中定义方法时,它在 main 的上下文中被私有化了。

还请注意,您可以使用 Object#send,但这将允许访问私有和公共方法(这可能是取决于使用情况的安全问题)

另一种选择是将 ab 定义为 lambdas 或 Procs,例如

a= ->(val) {puts "method a called with #{val}"}
b= ->(val) {puts "method b called with #{val}"}
def c(f1,f2)
  f1.call(123)
  f2.call(234)
end
c(a,b)
#method a called with 123
#method b called with 234
#=> nil   

【讨论】:

    【解决方案2】:

    有一个method 方法可以将函数转换为方法,所以我们可以这样做:

    def A a
    end
    
    def B b
    end
    
    def C( f1, f2 ) # this one ok
      f1.call 123
      f2.call 234
    end
    
    C( method(:A), method(:B))
    

    【讨论】:

    • “将函数转换为方法”没有意义。前者是在 Ruby 上下文中调用后者的非正式/错误方式。
    猜你喜欢
    • 2010-10-01
    • 2015-02-17
    • 2015-04-07
    • 2021-06-02
    • 2016-02-27
    • 2010-10-24
    • 2011-01-28
    • 2011-02-12
    • 1970-01-01
    相关资源
    最近更新 更多