Skip to content
loading...

A few ruby tricks for arrays and hashes

aidanlincoln profile image AidanLincoln github logo ・1 min read

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

Example:

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.

Example:

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

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.

Example:

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

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

twitter logo DISCUSS (1)
Discussion
markdown guide
Classic DEV Post from Aug 13 '19

How open-source will Tumblr become?

In case you hadn't read the news, Verizon sold Tumblr to Automattic. Verizon owned Tumblr after it ac...

AidanLincoln profile image