views:

91

answers:

2

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

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

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?

A: 

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:

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.

bennybdbc
yes, but `x=(5)` and `x=("5")` are all valid (the parentheses was just put in as possible disambiguation) so why not `x=("key" => "value")` Why can you put this in an array but not straight into a variable?
Earlz
@Earlz - you can't put that straight into a variable as it isn't like a string or number in that way. It shows an association between 2 items in a hash. It seems that when you initialise it in an array, it converts it to a hash, but when you try to put it into a variable it doesn't
bennybdbc
+2  A: 

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.

maerics
wow that's very odd..
Earlz
This is the closest answer. It's just part of the syntax. Chatted some in #RubyOnRails to discover that it is part of the Ruby grammar.
Earlz