我正在开发一个可以使用不同版本的 Gherkin 的 gem,但我遇到了一个问题: 在 2.4.0 版本中,Gherkin::Formatter::Model::Scenario.new 需要 6 个参数,但在 2.6.5 中需要 7 个参数。
所以我的问题是在这种情况下什么是最佳实践?我应该怎么做:
case Gherkin::Version
when '2.4.0'
do the init with 6 arguments
else
with the 7
end
我也在考虑创建一个 new_with_arity 方法:
class Object
def new_with_arity(*params)
puts method(:initialize).arity # => -1
puts method(:new).arity # => -1
new(*(params + [nil] * (params.count - method(:new).arity)))
end
end
但是这不起作用,new 和 initialize 的元数是 -1。 你有想法吗?
最佳答案
我建议听从 Jim Deville 的建议。说这是一个非常有趣的想法,而且你非常接近。问题是没有实例就无法获取方法,所以诀窍是先使用分配。
class Object
def new_with_arity(*params)
new *(params + [nil] * (allocate.method(:initialize).arity - params.size))
end
end
class One
def initialize a
[a]
end
end
class Two
def initialize a, b
[a, b]
end
end
One.new_with_arity 1 #=> [1]
Two.new_with_arity 1, 2 #=> [1, 2]
Two.new_with_arity 1 #=> [1, nil]
关于ruby - 在 Ruby 中为 new 使用正确数量的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8192511/