What is the different of `Hash Literal` with Tuple Array?

Following is a example:

x = {'x' => 100, 'y' => 200} 

x.each do |k, v|
  p k, v
end

x = [{'x', 100}, {'y', 200}]

x.each do |k, v|
  p k, v
end

Both of them result is same:

'x'
100
'y'
200

so, i am curious, if both of them is equivalent … but our document seem like not mention this.

Thank you.

EDIT: please check following discuss too, i consider this is a inconsistency bug in crystal?

This is working by design. See Blocks and Procs - Crystal.

Sorry, i knew this, and, you are not answer any of my question. :joy:

  1. {β€˜x’ => 100, β€˜y’ => 200} if same as [{β€˜x’, 100}, {β€˜y’, 200}] in internal implementation?

  2. why auto-splating for Hash(Symbol, Array(String)) not works on ECR <%= ??? %> context?

Unpacking block args would be a compiler feature I’d say yes

Because this feature only works with tuples, not arrays. As the docs point out, it’s a feature when yielding a tuple, the compiler automatically unpacks them. The hash case works because it passes the key and value as a two member tuple as part of its implementation.

EDIT: Tho I think using an array would work, you’d just have to do something like .each do |key, (arg1, arg2)|. I.e. use parentheses to manually unpack the arguments. E.g.

hash = {"foo" => [1, 2, 3]}

hash.each do |key, (arg1, arg2)|
  pp key, arg1, arg2 # => "foo", 1, 2
end

EDIT2: Yea

That means that any type that responds to [] with integers can be unpacked in a block parameter.

I think the question is: are the both structures equivalent? They look like dictionaries.

The answer is: no.

For instance, try getting the value associated to a key.

x = {'x' => 100, 'y' => 200} 
x['x'] # => 100

But:

x = [{'x', 100}, {'y', 200}]
x['x'] # Error: no overload matches 'Array(Tuple(Char, Int32))#[]' with type Char

Another answer: both types have an each method. But they are completely different types. It’s similar to asking what’s the difference between 1 and β€œ1” if calling to_s on both gives β€œ1”. Answer: completely different types that happen to have a method with the same name and that produce the same value.

4 Likes

You are still not answer my question. :rofl:

Please check this thread.

For this issue, my code is wrong, one low level error!

No questions for now, thank you all.