AidanofVT
AidanofVT

Reputation: 57

Can't understand why this code to convert a simple array into a simple hash isn't working

Code attached below.

 arrayy = [[1,'one'],[2,'two'],[3,'three']]
 hashy = {}
 i = 0
 arrayy.each do
   hashy[arrayy[i,0]] = arrayy [i,1]
   i = i+1
 end
 puts hashy[1]
 puts hashy[2]
 puts hashy[3]
end

This code doesn't output anything. No errors. So, I'm guessing that the problem is that nothing is being added to the hash.

Upvotes: 0

Views: 52

Answers (2)

tadman
tadman

Reputation: 211740

You're requesting zero elements, which is an empty array, so you're keying everything on an empty array and all elements collide. To fix that, just use the iterator, as each gives you the elements you need:

arrayy = [[1,'one'],[2,'two'],[3,'three']]

hashy = {}
arrayy.each do |key, value|
  hashy[key] = value
end

p hashy
# => {1=>"one", 2=>"two", 3=>"three"}

In your code the actual result you're getting is this:

p hashy
# => {[]=>[[3, "three"]]}

Where here you can see the [] key being used. The p method is really handy for looking at the internal structure of something. p hashy is equivalent to puts hashy.inspect.

As Sergio points out you were probably referencing the arrays the wrong way. To navigate two levels deep you do this:

hashy[arrayy[i][0]] = arrayy [i][1]

Where [i,0] means "at index of the array i select the next 0 elements" whereas [i][0] means "at the array at index i select the value at index 0".

It's worth noting that the simplest solution is to use Array#to_h which already does this:

arrayy = [[1,'one'],[2,'two'],[3,'three']]

hashy = array.to_h

p hashy
# => {1=>"one", 2=>"two", 3=>"three"}

Upvotes: 4

jong park
jong park

Reputation: 121

Not sure what you are trying to achieve here, but when you are doing arrayy[i,0] in the loop, you are saying that you want to grab zero elements.

When you pass in two numbers as the argument against an array, the first number is the index of the target value and the second number is the length. For example:

arr = ['a', 'b', 'c', 'd', 'e']
puts arr[2, 3] 

This would put out ['c','d','e'], which is 'starting from the element with index 2, grab 3 elements'.

Upvotes: 6

Related Questions