Aaron
Aaron

Reputation: 4480

printing out the values of a hash coming from an array

I have a hash called sales_hash that I am printing out. Each hash has a key called sku that matches a hash inside the array of array_items. I get the hash out of the array and am trying to print the values of the hash based on the key which is :item but I keep getting an error. What am I doing wrong?

sales_hash.take(10).each do |a, b|
  temp_hash = array_items.select{|array_items| array_items[:sku] == a}
  puts temp_hash
  puts "Sku is #{a} the amount sold is #{b} the name of the book is #{temp_hash[:price]}"
end

The line #{temp_hash[:item]}" keeps giving me an error

Upvotes: 0

Views: 70

Answers (3)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34336

As your temp_hash is an array, so you can access the expected hash like this:

temp_hash[0] # this will give you the expected hash data

And, then you can access the required key inside the hash (e.g. price):

temp_hash[0][:price]

Upvotes: 1

rotvulpix
rotvulpix

Reputation: 466

Since temp_hash is an array, and you're sure that there's only one item inside that array, the proper way to get the content of temp_hash is using "first" like this:

#{temp_hash.first[:price]}

Upvotes: 1

lcguida
lcguida

Reputation: 3847

Your temp_hash is actually an array.

From the Docs:

select -> Returns a new array containing all elements of ary for which the given block returns a true value.

And you can't access and array like this: array[:key].

Upvotes: 1

Related Questions