简体   繁体   English

Ruby:使用键/值数组设置新哈希

[英]Ruby: setting a new hash with an array of keys/values

(--工作人员删除的问题--)

Is this an example of the difference between class methods and instance methods?这是类方法和实例方法之间区别的示例吗?

Exactly.确切地。

But why can this be shortened to just Hash[*order] ?但是为什么这可以缩短为Hash[*order]

Ruby interprets some_object[] as a call to the method named [] on some_object . Ruby 将some_object[]解释为对some_object上名为[]的方法的调用。 This isn't special for Hashes, you can implement a [] method in any class of your own and use that syntax.这对于哈希并不特殊,您可以在您自己的任何类中实现[]方法并使用该语法。

Can someone explain what's going on here, and if there are alternate ways to add values from an array into a hash?有人可以解释这里发生了什么,以及是否有其他方法可以将数组中的值添加到哈希中?

Hash[*order] calls a class method ( Hash#[] ) which creates a new Hash. Hash[*order]调用一个类方法( Hash#[] )来创建一个新的 Hash。 o.[](*order) doesn't work for the same reason you can't call new on it: {}.new doesn't make any sense. o.[](*order)不起作用的原因与您不能对其调用new原因相同: {}.new new没有任何意义。 You can't call a class method on an instance of the class.您不能在类的实例上调用类方法。

You can add values with merge :您可以使用merge添加值:

o = Hash.new
o.merge(Hash[*order])

o = {*order} doesn't work because {} is the syntax for a Hash literal, and putting *order in there doesn't make sense. o = {*order}不起作用,因为{}是哈希文字的语法,将*order放在那里没有意义。

Hash(*order) is Kernel#Hash , a method that expects only one argument. Hash(*order)Kernel#Hash ,一种只需要一个参数的方法。

When you write Hash(*order) you're actually calling the Hash method in the Kernel module, which is not the same as calling the [] method in the Hash class.当你写Hash(*order)你实际上是在调用Kernel模块中的Hash方法,这与调用Hash类中的[]方法是不一样的。 See the docs for Kernel#Hash to see what's going on under the hood there.请参阅Kernel#Hash文档以了解那里发生了什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM