ruby中的方法指针

Pet*_*ter 16 ruby

我想在Ruby中的数组中存储几种不同的方法.假设我想将type方法存储两次:

[type, type]
Run Code Online (Sandbox Code Playgroud)

不存储type数组中的两个条目; 它执行type两次,并将结果存储在数组中.我如何明确地引用方法对象本身?

(这只是我真正想要的简化版本.)

编辑:在第二个想法,困扰我,下面提出的解决方案通过传递方法的名称避免了问题.你如何传递方法对象本身?例如,如果将[:type,:type]传递给具有替代分辨率类型的方法,该怎么办?你怎么能传递类型方法对象本身?

Chu*_*uck 33

如果要存储方法而不是调用方法的结果,或者只是存储要调用它的消息,则需要method在拥有对象上使用该方法.所以举个例子

"hello".method(:+)
Run Code Online (Sandbox Code Playgroud)

将返回对象"hello"的+方法,这样如果你用参数"world"调用它,你就会得到"hello world".

helloplus = "hello".method(:+)
helloplus.call " world" # => "hello world"
Run Code Online (Sandbox Code Playgroud)


Aug*_*aas 13

如果您正在考虑在Ruby中进行方法引用,那么您做错了.

Ruby中有一个内置的方法叫做method.它将返回该方法的proc版本.但它不是对原始方法的引用; 每次调用method都会创建一个新的proc.例如,更改方法不会影响proc.

def my_method
  puts "foo"
end

copy = method(:my_method)

# Redefining
def my_method
  puts "bar"
end

copy.call
# => foo
Run Code Online (Sandbox Code Playgroud)

如果要存储代码片段,并且不想使用常规方法,请使用procs.

stack = [proc { do_this }, proc { do_that }]
stack.each {|s| s.call }
Run Code Online (Sandbox Code Playgroud)