Marrento
Marrento

Reputation: 329

Loop through hash in Ruby

My search returns this hash bellow {"product"=>[{:title=>"It's All About Shoes Barbie Shoe Tree 2010 Hallmark Ornament"}, {:title=>"Iron Lady Bug Key Holder - Hide-A-Key"}]}

here is the loop and the code that generates the hash

id = "B003TM2IDS,B004X75EX4"
ids = id.split(',')

response = []
prod = Hash.new
product = Hash.new

#fetch product title from amazon
for aid in ids do
 res = Amazon::Ecs.item_lookup(aid, { :response_group => "ItemAttributes"})
 res.items.each do |item|
   prod[:title] = item.get("ItemAttributes/Title")
 end

 # hash
 product = {"product" => response.push(prod.dup)}
end

#loop to print the titles - Not working
product.each do |item_prod|
  puts item_prod.title
end

I do get the undefined method `title' for # (NoMethodError)

My question are:

I've done this millions of times but some reason I can't see the problem with this

Thanks a lot in advance

Upvotes: 0

Views: 148

Answers (2)

Rafa Paez
Rafa Paez

Reputation: 4870

product["product"].each { |p| puts p[:title] }

Upvotes: 1

bjhaid
bjhaid

Reputation: 9782

Do as below:

product["product"].each do |prod| 
  puts prod[:title]
end

Upvotes: 2

Related Questions