gpt4 book ai didi

ruby - 如何在 Ruby 中调用方法作为参数?

转载 作者:太空宇宙 更新时间:2023-11-03 17:48:19 25 4
gpt4 key购买 nike

我一直在阅读有关在 Ruby 中传递方法的不同方法,对我来说传递方法并在其上执行似乎是最干净的方法。但是,我认为我做错了。这有效:

def core
myMethod = rand(2) > 0 ? meth1 : meth2
myMethod.call("entered val")
end

def meth1
Proc.new do | val |
puts "meth1: #{val}"
end
end

def meth2
Proc.new do | val |
puts "meth2: #{val}"
end
end

但是看起来像下面这样感觉更自然(这不起作用):

def core
myMethod = rand(2) > 0 ? meth1 : meth2
myMethod("entered val")
end

def meth1
puts "meth1: #{val}"
end

def meth2
puts "meth2: #{val}"
end

如何格式化后者以使其正常工作?

最佳答案

您的第二个示例不起作用,因为您实际上是在三元运算符中从 core 调用 meth1meth2。您可以使用 Object#method方法从您的各个方法中创建一个 Method 对象实例。哇。 method 这个词用了很多。示例代码:

def core
myMethod = rand(2) > 0 ? method(:meth1) : method(:meth2)
myMethod.call("entered val")
end

def meth1(val)
puts "meth1: #{val}"
end

def meth2(val)
puts "meth2: #{val}"
end

core
# => "meth1: entered val" (or "meth2: entered val")

另一种选择是使用 Object#public_sendObject#send像这样:

def core
myMethod = rand(2) > 0 ? :meth1 : :meth2
send(myMethod, "entered val")
end

def meth1(val)
puts "meth1: #{val}"
end

def meth2(val)
puts "meth2: #{val}"
end

如果您的方法可见性允许,请首选 public_send

关于ruby - 如何在 Ruby 中调用方法作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30201419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com