In Ruby code, I was confused for a moment as "Hash-like but parentheses are arrays?"

I was confused when I saw such a piece of code in Ruby.

obj = [ a: "b", x: "y" ]

The parentheses are for the ** array **, but the contents are written as ** hashes **.

It's a code that actually works in business, so it's definitely not a syntax error.

answer

You can see it immediately by executing it with irb etc. The equivalent code is below.

Click to expand
obj = [{ a: "b", x: "y" }]
#=> [{:a=>"b", :x=>"y"}]

In short, an "array whose elements are hashes".


In retrospect, I was able to ** omit the hash curly braces ** at the end of the method call arguments. Array literals may be treated in the same way as arguments.

def mtd(*args)
	p args
end

mtd 1, 2, a: "b", x: "y"
#=> [1, 2, {:a=>"b", :x=>"y"}]

Recommended Posts

In Ruby code, I was confused for a moment as "Hash-like but parentheses are arrays?"
I translated [Clone method for Java arrays] as the Clone method in Java arrays.
I searched for a web framework with Gem in Ruby
I was confused because there was a split in the Array
I tried to write code like a type declaration in Ruby
I tried a calendar problem in Ruby
I made a Ruby extension library in C
Make a snippet for Thymeleaf in VS Code
Summary of what I was pointed out after receiving a code review as a beginner