Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Ruby中为new使用正确数量的参数_Ruby_Metaprogramming - Fatal编程技术网

在Ruby中为new使用正确数量的参数

在Ruby中为new使用正确数量的参数,ruby,metaprogramming,Ruby,Metaprogramming,我正在开发一种可以使用不同版本的小黄瓜的宝石,但我面临一个问题: 在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 我也在考虑创建一个新的“使用”方法: class Ob

我正在开发一种可以使用不同版本的小黄瓜的宝石,但我面临一个问题: 在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
我也在考虑创建一个新的“使用”方法:

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。
你有什么想法吗?

我会制作两个小黄瓜适配器,然后为正确的版本加载正确的适配器。或者,您使用的是Rubygems,因此可以强制使用特定版本的小黄瓜解析器

我建议遵循Jim Deville的建议。说这是一个很有趣的想法,而你很接近。问题是,如果没有实例,就无法获得该方法,因此技巧是首先使用allocate

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]