user3576036
user3576036

Reputation: 1425

Looping an array and storing the values to a hash in ruby

I am trying to loop an array which might look like following:

names = ['sid','john'] #this array will  be dynamic, The values keep changing

I am trying to write a method where I will define an empty hash and loop the array using .each and then store the values to hash.But not working.

def add_address
 names = ['sid','john']
 addr_arr = {}
 names.each do |n|
  addr_arr['name'] = n
 end
addr_arr
end

this returns only {"name"=>"john"}. What am I doing wrong?

Upvotes: 0

Views: 548

Answers (2)

Ursus
Ursus

Reputation: 30056

If you always use the key 'name', you're overwriting its values every time, I don't think that's what you want. I don't know if this is what you want anyway, but this should be enough to understand the problem

names.each do |n|
  addr_arr[n] = n
end

Upvotes: 1

Viktor
Viktor

Reputation: 2773

The problem with your implementation is that there's only one hash and each time you set a value for the "name" key, the previous value for that key will be deleted and replaced by the new value.

I see addr_arr has arr in the name, so I assume you wanted something like this:

def add_address
 names = ['sid','john']
 addr_arr = []
 names.each do |n|
  addr_arr << { "name" => n}
 end
addr_arr
end

add_address
#=> [{"name"=>"sid"}, {"name"=>"john"}]

or shorter:

['sid','john'].map{ |name| {"name" => name} }
#=> [{"name"=>"sid"}, {"name"=>"john"}]

Upvotes: 2

Related Questions