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"
Ruby prior to 1.9 didn't maintain the "insertion" order of hashes. Here's a way to force a known order, without relying on sorting:
That returns just the values, in their desired order.
Here's how to process the hash in that same order:
Here's another way to look at it...
Enumerable's
zip
lets us join two arrays' elements, interweaving them:We can pass the output from
zip
tomap
to add in whether the prices is "more" or "less":Look at the contents of
groceries
: An array-of-arrays is exactly the sort of data you'd want to pass to a view if you were rendering a web-page using ERB or Haml.Then we can generate some output strings and print them:
Using a format-string is akin to an ERB or Haml template. This is just a couple steps away from how ERB/Haml got their start.
I broke the above into smaller steps, but the actual process could be written: