Inconsistent implicit hash creation in Ruby?
Ok, so I compared some things in my own DSL with Ruby. One design they support is
x=["key" => "value"] Knowing the difference between arrays and hashes, I think this is illegal, but the result in Ruby
[{"key" => "value"}] Why is this? And with this peculiar syntax, why can't you do
x=("key" => "value") Why is an array a special case for implicitly generated hashes?
Another special case is a function call:
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 believe the answer is that it was Matz’s least surprising behavior.
With this apparent inconsistency in the implicit creation of the hash, the ruby achieves consistency in this regard:
func(whatever...) can always be replaced by:
args = [whatever...] func(*args) You can convert between argument lists and arrays, and so it makes sense that they have the same syntax.
I would say that the interpreter finds out that the "key" => "value" is a hash, just as it turns out that 5 is a number when you put it in an array.
Therefore, if you write:
x = [5] The interpreter is not going to think that this is a string, and returns:
x = ["5"] Ruby seems to implicitly create hashes in some cases.