【问题标题】:Ruby keyword as named hash parameterRuby 关键字作为命名散列参数
【发布时间】:2015-06-01 08:38:37
【问题描述】:

是否可以使用新的 ruby​​ 2.0 语法访问包含关键字参数的哈希值?

class List::Node
  attr_accessor :data, :next
  def initialize data: nil, next: nil
    self.data = data
    self.next = next # ERROR! 
  end
end

旧语法可以正常工作:

class List::Node
  attr_accessor :data, :next
  def initialize options = { data: nil, next: nil }
    self.data = options[:data]
    self.next = options[:next] 
  end
end

----- 编辑-----

我意识到next 是一个保留字,但我猜测关键字属性在内部存储在哈希中,我想知道是否可以访问它,例如通过self.argsself.parametersself.options

【问题讨论】:

    标签: ruby ruby-2.0


    【解决方案1】:

    这将起作用:

    class List::Node
      attr_accessor :data, :next
      def initialize data: nil, _next: nil
        self.data = data
        self.next = _next
      end
    end
    

    next 是 Ruby 保留字。使用不是 Ruby 保留关键字的名称。

    编辑:是的,可能,但不是一个好主意。

    class List::Node
      attr_accessor :data, :next
      def initialize data: nil, next: nil
        self.data = data
        self.next = binding.local_variable_get(:next)
      end
    end
    p List::Node.new.next # nil
    

    local_variable_get

    【讨论】:

    • 这正是我想要的,谢谢!我从来没有把这段代码投入生产,但我正在玩 ruby​​ 试图更好地理解它。
    【解决方案2】:

    就像*args 收集你在参数列表中没有提到的所有位置参数一样,**kwargs 收集你没有提到的所有关键字参数在参数列表中。据我所知,没有一种简单的方法可以同时从声明的参数和 splat 访问位置参数,关键字参数也是如此。

    def foo(pos1, pos2, *args, reqkw:, optkw: nil, **kwargs)
      puts [pos1, pos2, reqkw, optkw, args, kwargs].inspect
    end
    foo(1, 2, 8, reqkw: 3, optkw: 4, extkw: 9)
    # => [1, 2, 3, 4, [8], {:extkw=>9}]
    

    即您只能从位置参数访问12,并且只能从 splat 访问 8;同样,您只能从关键字参数访问34,并且只能从双拼中访问9

    (Arup Rakshit 已经提供了通过符号访问参数的 hacky 方法 - 但请注意,这会访问所有局部变量,而不仅仅是参数。)

    【讨论】:

      【解决方案3】:

      错误是因为next 是一个Ruby 关键字。换个名字就好了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-10
        • 2019-10-03
        • 2023-04-08
        相关资源
        最近更新 更多