构造一个 Ruby 对象,returns 调用它的方法的名称
Construct a Ruby object that returns the names of methods called on it
我想构造一个 Ruby 对象,它具有以下内容 属性:对于任何方法名称,当该方法名称传递给对象时,return 值是字符串形式的方法名称。
这是一个有一些问题的尝试:
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"
我如何构造一个总是回显其传递的消息的对象。 (如果解决方案不需要在每次调用时都进行复杂的方法查找,则加分。)
怎么样:
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
我想构造一个 Ruby 对象,它具有以下内容 属性:对于任何方法名称,当该方法名称传递给对象时,return 值是字符串形式的方法名称。
这是一个有一些问题的尝试:
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"
我如何构造一个总是回显其传递的消息的对象。 (如果解决方案不需要在每次调用时都进行复杂的方法查找,则加分。)
怎么样:
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