我想创建一个实例方法,将其自身类的另一个实例方法作为参数,然后将传递的方法应用于它正在处理的实例(称为 self
):
class MyClass
attr_reader :called_methods
def initialize
@called_methods = []
end
def my_first_method!
@called_methods << :my_first_method
self
end
def my_second_method!
@called_methods << :my_second_method
self
end
def my_strange_method!(secondary)
# Want to apply method whose name is given by secondary, to self
end
end
p MyClass.new.my_second_method!.my_strange_method!(:my_first_method!).called_methods
我怀疑一元 &
可能是关键,但我能在该运算符上找到的所有网页都涉及对多个对象调用方法,例如迭代 Enumerable
使用 #each
或 #map
。
最佳答案
使用Object#public_send
(或 Object#send
以应用 protected /私有(private)方法)。
def my_strange_method!(secondary)
public_send(secondary)
self
end
p MyClass.new.
my_second_method!.
my_strange_method!(:my_first_method!).
called_methods
#⇒ [:my_second_method, :my_first_method]
如果且只有方法是已知的,可能会有更多的防御方法来应用:
def my_strange_method!(secondary)
raise ArgumentError.new("Unknown method #{secondary}") \
unless methods.include? secondary.to_s.to_sym
public_send(secondary)
end
p MyClass.new.
my_second_method!.
my_strange_method!(:my_first_method!).
called_methods
#⇒ [:my_second_method, :my_first_method]
p MyClass.new.
my_second_method!.
my_strange_method!(:inexisting_method!).
called_methods
#⇒ ArgumentError: Unknown method inexisting_method!
关于Ruby 相当于 lisp-like "apply"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54351638/