不一致的隐含哈希创建Ruby的? [英] Inconsistent implicit hash creation in Ruby?
问题描述
好了,我在我自己的DSL来比较Ruby的一些东西。一个构建它们都支持本
Ok, so I was comparing some stuff in my own DSL to Ruby. One construct they both support is this
x=["key" => "value"]
了解数组和哈希的区别,我认为这是非法的,但结果在Ruby是
Knowing the difference between arrays and hashes, I would think this to be illegal, but the result in Ruby is
[{"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?
推荐答案
另一种特殊情况是在一个函数调用,考虑:
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.
这篇关于不一致的隐含哈希创建Ruby的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!