Reputation: 53
I'm trying to figure out how to print just the key in a Hash right now. I'm still new to this and I'm missing something on how to just print the key. My code so far:
shopping_list = {
'milk' => false,
'eggs' => false,
'jalapenos' => true
}
puts "Here is your shopping list!"
shopping_list.each do |key|
puts "- #{key}"
end
My output:
Here is your shopping list!
- ["milk", false]
- ["eggs", false]
- ["jalapenos", true]
I just want to value to print out like:
Here is your shopping list!
- milk
- eggs
Eventually, I would like to leave out the true shopping item, in this instance, it would already be purchased. I would like to print out what I still need to buy first.
Upvotes: 2
Views: 62
Reputation: 1449
You can get values you want by combining #reject
, #keys
and #each
methods like below:
shopping_list.reject { |key, value| value }.keys.each do |key|
puts "- #{key}"
end
As Cary Swoveland mentioned, the code above was created temporary arrays. If you don't want to created those, you can use the code below:
shopping_list.each do |key, value|
puts "- #{key}" if value == false
end
Upvotes: 2
Reputation: 53
Figured it out.
shopping_list = {
'milk' => false,
'eggs' => false,
'jalapenos' => true
}
puts "Here is your shopping list!"
for key in shopping_list.keys()
puts "- #{key}"
end
My output.
Here is your shopping list!
- milk
- eggs
- jalapenos
Upvotes: 0