Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inconsistent implicit hash creation in Ruby?

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?

like image 778
Earlz Avatar asked May 15 '10 01:05

Earlz


2 Answers

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.

like image 186
maerics Avatar answered Oct 14 '22 02:10

maerics


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

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.

like image 35
jonas054 Avatar answered Oct 14 '22 01:10

jonas054