This is a simple homework assignment....
Given a hash that looks like this:
cost_of_groceries = {
"milk" => 3.50,
"egg" => 1.50,
"broccolli" => 0.75
}
I want to print out which groceries are less than $2 and which groceries are more than $2. This would be a sample output:
milk is more than $2
eggs is less than $2
broccolli is less than $2
Not a problem, but this is not printing in the correct order using Ruby 1.8.7.
My code:
cost_of_groceries.each do |x,y|
if y > 2
puts "#{x} is more than $2"
else
puts "#{x} is less than $2"
end
end
This is what I get:
broccolli is less than $2
egg is less than $2
milk is more than $2
=> {"broccolli"=>0.75, "egg"=>1.5, "milk"=>3.5}
I realize pre-1.9 Ruby does not maintain the order of iteration on a Hash, and I know I can just use different version to solve this, but I was hoping to dig into this and learn an alternate method for pre-1.9.3. I never know when it might come in handy.
This is a similar post: "Ruby maintain Hash insertion order"
this is what I have been able to mashup: it works but violates the context of homework question: