8

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?

0

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
2

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.

Comments

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:

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.

2 Comments

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 - 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.