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

时间:2021-08-11 09:20:39

I've been reading up on different ways to pass methods in Ruby, it seems the cleanest to me to pass the method and execute on it. However, I think I'm doing it incorrectly. This works:

我一直在阅读在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

But it feels more natural to have it look like the below (which doesn't work):

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

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

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

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

How do I format the latter so it works properly?

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

1 个解决方案

#1


Your second example doesn't work because you are actually calling meth1 and meth2 from core in your ternary operator. You can use the Object#method method to make a Method object instance out of your individual methods. Wow. That's a lot of using the word method. Example code:

你的第二个例子不起作用,因为你实际上是在你的三元运算符中从核心调用meth1和meth2。您可以使用Object#方法方法从各个方法中生成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")

Another option would be to use Object#public_send or Object#send like so:

另一种选择是使用Object#public_send或Object#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

Prefer public_send if your method visibility allows it.

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

#1


Your second example doesn't work because you are actually calling meth1 and meth2 from core in your ternary operator. You can use the Object#method method to make a Method object instance out of your individual methods. Wow. That's a lot of using the word method. Example code:

你的第二个例子不起作用,因为你实际上是在你的三元运算符中从核心调用meth1和meth2。您可以使用Object#方法方法从各个方法中生成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")

Another option would be to use Object#public_send or Object#send like so:

另一种选择是使用Object#public_send或Object#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

Prefer public_send if your method visibility allows it.

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