Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an array containing a hash

QUESTION EDIT - Breakdown how the 2nd example creates a hash.

I can't figure out why the first example below does not create a hash and the second one does.

a: :b
# => SyntaxError: (irb):1: syntax error, unexpected ':', expecting end-of-input

vs.

[a: :b]
# => [{:a => :b}]
like image 804
omgmakeme Avatar asked Nov 30 '25 06:11

omgmakeme


1 Answers

When you just have a: :b that is a statement and it is invalid Ruby syntax.

When you have [a: :b], you are actually calling a method. The method you are calling is [](a: :b). When you give a: :b as the argument to a method Ruby sees it as a hash and gives the method {:a => :b} as it's argument. So the end result is the [{:a => :b}] that you are seeing.

like image 168
Alex Peachey Avatar answered Dec 02 '25 21:12

Alex Peachey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!