Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/git/20.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关键字作为命名哈希参数_Ruby_Ruby 2.0 - Fatal编程技术网

Ruby关键字作为命名哈希参数

Ruby关键字作为命名哈希参数,ruby,ruby-2.0,Ruby,Ruby 2.0,是否可以使用新的ruby 2.0语法访问hash-holding关键字参数 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 initi

是否可以使用新的ruby 2.0语法访问hash-holding关键字参数

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.args
self.parameters
self.options
,等等。

错误是因为
next
是一个Ruby关键字。选择另一个名称就可以了。

这将起作用:

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

看。

就像
*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}]
也就是说,您只能从splat访问
1
2
作为位置参数,以及
8
;同样,只能从关键字参数访问
3
4
,只能从doublesplat访问
9


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

这正是我想要的,谢谢!我从来没有把这段代码放到生产环境中,但我一直在玩ruby,试图更好地理解它。