DEV Community


Posted on

A few ruby tricks for arrays and hashes

  • You can create a hash from a list of keys and values by using Hash[key, value].


Hash[‘key1’, ‘value1’, ‘key2’, ‘value2’]

=> {‘key1’=>’value1’, ‘key2’=>’value2’}

  • You can directly turn parameters into arrays or hashes using a single star or double star in a method’s parameters.

The single star(arg*) takes all arguments after its call, and stores them in an array.

The double star(arg**) expects you to pass in a key value pair, and stores it in a hash.


def new_method(a, b*, c**)
return a, b, c

new_method(1, 2, 3, 4, a: 5, b: 6)

=> [1, [2, 3, 4], {:a => 5, :b => 6}]

  • Lastly, I found out that any object can be used as a key in a hash.


Hash[true, ‘stuff’, false, ‘other stuff’]

=> {true=>’stuff’, false=>’other stuff’}

Top comments (1)

jricecake profile image
Jonny Riecke

Nice one Aidan!!!!