[翻译]  Inconsistent implicit hash creation in Ruby?

[CHINESE]  Ruby中隐式哈希创建不一致?


Ok, so I was comparing some stuff in my own DSL to Ruby. One construct they both support is this

好的,所以我将自己DSL中的一些东西与Ruby进行了比较。他们都支持的一个结构就是这个

x=["key" => "value"]

Knowing the difference between arrays and hashes, I would think this to be illegal, but the result in Ruby is

知道数组和散列之间的区别,我认为这是非法的,但Ruby中的结果是

[{"key" => "value"}]

Why is this? And with this kinda syntax why can't you do

为什么是这样?有了这种语法,为什么你不能这样做

x=("key" => "value") 

Why is an array a special case for implicitly created hashes?

为什么数组是隐式创建哈希的特例?

3 个解决方案

#1


2  

Another special case is in a function call, consider:

另一个特例是在函数调用中,考虑:

def f(x)
  puts "OK: #{x.inspect}"
end
f("foo" => "bar")
=> OK: {"foo"=>"bar"}

So in some contexts, Hashes can be built implicitly (by detecting the => operator?). I suppose the answer is just that this was Matz's least-surprising behavior.

所以在某些情况下,可以隐式构建哈希(通过检测=>运算符?)。我想答案就是这是Matz最不令人惊讶的行为。

#2


2  

With this apparent inconsistency in implicit hash creation, ruby achieves consistency in this regard:

由于隐式哈希创建明显不一致,ruby在这方面实现了一致性:

func(whatever...)

can always be substituted with:

总是可以用以下代替:

args = [whatever...]
func(*args)

You can convert between argument lists and arrays, and therefore it is logical that they have the same syntax.

您可以在参数列表和数组之间进行转换,因此它们具有相同的语法是合乎逻辑的。

#3


0  

I would say that the interpreter figures out that "key" => "value" is a hash, the same way it would figure out that 5 is a number when you put it into an array.
So if you write:

我会说解释器会发现“key”=>“value”是一个哈希值,就像你将它放入一个数组时弄清楚5是一个数字一样。所以,如果你写:

x = [5]

The interpreter is not going to think that it is a string, and return:

解释器不会认为它是一个字符串,并返回:

x = ["5"]

It seems that ruby implicitly creates hashes in some instances.

似乎ruby在某些情况下隐式地创建了哈希。


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2018 ITdaan.com 粤ICP备14056181号