Ruby 2.1: la méthode Array#to_h
La version 2.1 de Ruby est sortie comme promis à Noël. La classe Array y gagne
une nouvelle méthode: to_h
.
Pour transformer ce tableau:
[[:key1, "one"], [:key2, "two"], [:key3, "three"]]
en un Hash:
{:key1=>"one", :key2=>"two", :key3=>"three"}
La méthode était jusqu’ici la suivante:
>> my_array = [[:key1, "one"], [:key2, "two"], [:key3, "three"]]
>> Hash[*my_array.flatten]
=> {:key1=>"one", :key2=>"two", :key3=>"three"}
Ruby 2.1 rend ceci plus simple, plus lisse, en ajoutant une méthode
de transformation à la classe Array, to_h
:
>> my_array.to_h
=> {:key1=>"one", :key2=>"two", :key3=>"three"}
À demain.
/ / / / / / / / / /