PullMonkey Blog

03 May

Converting ruby Array to Hash


I ran across a situation that required the know-how of converting an array into a hash.

Converting a hash into an array (obvious):

1
2
3
4
  >> hash = {"a" => 1, "b" => 2, "c" => 3}
  => {"a"=>1, "b"=>2, "c"=>3}
  >> array = hash.to_a
  => [["a", 1], ["b", 2], ["c", 3]]

Now back to hash from an array, you could try array.to_h, or array.to_hash, but apparently not.

1
2
  >> hash2 = Hash[*array.flatten]
  => {"a"=>1, "b"=>2, "c"=>3}

The * of *array converts array into an assignment list.

The * opperator can also be used on the left side of the assignment:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  irb(main):001:0> a = ["1","2","3","4"]
  => ["1", "2", "3", "4"]
  irb(main):002:0> b,c = a
  => ["1", "2", "3", "4"]
  irb(main):003:0> b
  => "1"
  irb(main):004:0> c
  => "2"
  irb(main):008:0> b,*c = a
  => ["1", "2", "3", "4"]
  irb(main):009:0> b
  => "1"
  irb(main):010:0> c
  => ["2", "3", "4"]

Notice how using the * in front of c made it a list, in otherwords, c contains the remainder of elements in a after b got its assignment.

Neat, eh?



Filed under: Home, development, ruby

Sorry, comments for this entry are closed at this time.