构造一个Ruby对象,该对象返回在其上调用的方法的名称

时间:2017-11-11 23:25:42

标签: ruby string metaprogramming

我想构造一个具有以下属性的Ruby对象:对于任何方法名称,当该方法名称传递给对象时,返回值是方法名称作为字符串。

这是一个有一些问题的尝试:

class Echo < BasicObject
  def self.method_missing(the_method)
    the_method.to_s
  end
end

Echo根据需要响应大多数方法调用:

> Echo.foo
 => "foo" 
> Echo.send("Hello world.")
=> "Hello world." 

Echo继承自BasicObject,因此它以正常方式响应其超类'方法:

> Echo.to_s
=> "Echo"

如何构造一个总是回显它传递的消息的对象。 (如果解决方案在每次调用时都不需要复杂的方法查找,则会获得奖励。)

1 个答案:

答案 0 :(得分:1)

怎么样:

class Echo
  class << self
    def method_missing(the_method)
      the_method.to_s
    end

    methods.each do |name|
      define_method(name) do |*any|
        name.to_s
      end
    end
  end
end

试验:

RSpec.describe Echo do
  it "returns a missing method as a string" do
    expect(described_class.some_method_that_doesnt_exist).
      to eq("some_method_that_doesnt_exist")
  end

  it "returns an existing method as a string" do
    expect(described_class.to_s).
      to eq("to_s")
  end
end
相关问题