代码在Ruby 2.7中运行良好,但在Ruby 2.6.3中却无法运行

时间:2020-08-18 06:35:54

标签: ruby ruby-2.6 ruby-2.7

我已经在Ruby 2.7中编写了具有装饰器功能的代码。它在该版本中运行良好,但是相同的代码在Ruby 2.6中无法正常工作。如果我取消对装饰器的调用,即wrapper_function,则代码将在Ruby 2.6中执行,但这不是我想要的功能。那么我在这里的错误是什么,我该如何纠正?

已编辑

#test.rb

FAMILYTREE = {
  "name": "Royal Family",
  "members": [
    [
      "King",
      "Male",
      "no mother"
    ],
    [
      "Queen",
      "Female",
      "no mother",
      "King"
    ]
    
  ]
}

module Wrapper
  def wrapper_function(func_name)
    new_name_for_old_function = "#{func_name}_old".to_sym
    alias_method(new_name_for_old_function, func_name)
    define_method(func_name) do |*args, **kwargs|
      begin
        result = send(new_name_for_old_function, *args, **kwargs)
        if result.instance_of?(Array) && result.any?
          result.map(&:name).join(' ')
        end
      end
    end
  end
end

class Person
  attr_accessor :name, :gender, :mother

  def initialize(name, gender, mother_name=nil)
    @name = name
    @gender = gender
    @mother = mother
  end

end

class Family
  extend Wrapper
  attr_accessor :family_name, :members

  def initialize(family_name)
    @family_name = family_name
    @members = []
  end

  def add_member(person_name, gender, mother_name, spouse_name)

    person = Person.new(person_name, gender, mother_name)

    members << person
  end
  wrapper_function(:add_member)
end


def create_family_tree(family_tree)
  #Initializing the family
  family_name = family_tree[:name]
  members = family_tree[:members]

  family = Family.new(family_name)
  members.each do |name, gender, mother_name, spouse_name|
    family.add_member(name, gender, mother_name, spouse_name)
  end
  family
end

fam = create_family_tree(FAMILYTREE)

以上是显示问题的完整文件: 要运行它:ruby test.rb 如果版本为2.7.1,则代码将正确执行。 如果是2.6.3,则出现此错误: test.rb:54:in add_member: wrong number of arguments (given 5, expected 4) (ArgumentError)

如果在wrapper_function的{​​{1}}和23行中删除了25,则程序将执行并以版本**kwargs给出所需的结果。那为什么会这样呢?

1 个答案:

答案 0 :(得分:2)

是-删除wrapper_function中的两个**kwargs使其可以在2.6.x和2.7.x中工作

Ruby 2.7 deprecating automatic conversion from a hash to keyword arguments

有关