Ruby Array#mirror convert an Array to an Hash

Lorenzo Sinisi bio photo By Lorenzo Sinisi Comment

Arrays in programming and specifically in the Ruby programming language are ordered collections of ‘things’.

An array looks like: ` [‘one’, ‘two’, ‘bear’, ‘unicorn’] `

An Hash instead is a collection of key-value pairs. It is similar to an Array, except that indexing is done via arbitrary keys of any type of thing.

An hash looks like: ` {‘one’ => ‘unos’, ‘two’ => ‘due’, ‘bear’ => ‘danger’, ‘unicorn’ => ‘exist’} ` Sometimes I needed to have a combination of both in my code. I needed to have an Hash were the keys and values were the same. To achieve this goal there are many ways, but I needed a method on top of the object Array that can mirror it. For instance, the result should have been:

  ['one', 'two', 'bear', 'unicorn'].mirror

  # resulting in {'one' => 'one', 'two' => 'two', 'bear' => 'bar', 'unicorn' => 'unicorn'}

So I created a gem called array_mirror. and by adding it to your gem file or installing and requiring it you can call the method Array#mirror and ‘mirror’ any Array. This is quite handy in forms and part of your code where you need to have an Array but in a structure of an Hash.

Add this gem to your Gemfile:

  gem 'array_mirror' # add the moethod [].mirror to Arrays
comments powered by Disqus