Ruby 相当于 lisp-like "apply"?

标签 ruby functional-programming

我想创建一个实例方法,将其自身类的另一个实例方法作为参数,然后将传递的方法应用于它正在处理的实例(称为 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/

相关文章:

scala - kind-projector 返回奇怪的结果

scala - 为什么 Scala 类型推断在这里失败

python - 词法分析和解析实用程序

scala - 在使用 State 和 IO 的堆叠 monad 时停止理解中流

javascript - 在 Heroku 上访问 Javascript 中的环境变量?

ruby - 在 Gemfile 中设置环境以根据自定义文件 bundle 安装/更新

swift - 如何将生产就绪的 ReactiveCocoa 或 Futures/Promises 添加到 Swift 2 iOS

scala - 如何在 Scala 中将多个函数作为可变参数?

ruby - 使用 SHA256 摘要签名的 OpenSSL RSA

ruby - 我的回文程序有什么问题? (Ruby,用户自己输入字符串)