# Simple looping question

I have some data in a YAML file that looks like:

20060712: [9.174, 131452]
20060719: [9.466, 131805]
20060727: [9.197, 132150]
20060807: [9.778, 132540]

It represents dates, gallons of gas, and mileage, respectively.

I want to loop through and print out something like:

The W gallons of gas purchased on X lasted Y days. The mileage was Z
miles per gallon.

What is the best way to do this? I need the next date from the next
entry in the hash, so a simple .each won’t work. I can’t quite wrap my

Thanks.

How about looping through the list backwards?

Aqua Fina wrote:

The W gallons of gas purchased on X lasted Y days. The mileage was Z
miles per gallon.

What is the best way to do this? I need the next date from the next
entry in the hash, so a simple .each won’t work. I can’t quite wrap my

You’ll need to figure out how to compare two dates, but I’m sure one of
the core classes has a way of accomplishing that. As for knowing which
date is next:

entries = hash.entries.sort_by{|date, *| date }
entries.each_with_index do |entry, i|
if i < entries.length
days = do_comparison(entry[0], entries[i + 1])

end
end

Cheers,
Daniel

equire ‘yaml’
require ‘enumerator’

data.entries.sort_by{|date, *| date }.each_cons(2) do | first, second |
date_first = DateTime.parse(second[0].to_s)
date_second = DateTime.parse(first[0].to_s)
duration = date_first - date_second
miles = second[1][1] - first[1][1]
miles_per_gallon = miles / first[1][0]
p “The #{first[1][0]} gallons of gas purchased on
#{date_first.strftime(’%m/%d/%Y’)} lasted #{duration.to_i} days. The
mileage was #{miles_per_gallon} miles per gallon.”
end

The key here is the each_cons coming from the enumerable mixin, which
iterates the array in pairs of twos.

Disclaimer: I am a German living in Australia, so if I got the date
format or the miles per gallon calculation wrong, blame the non-metric
system.

Max

Max M. wrote:

equire ‘yaml’
require ‘enumerator’

data.entries.sort_by{|date, *| date }.each_cons(2) do | first, second |
date_first = DateTime.parse(second[0].to_s)
date_second = DateTime.parse(first[0].to_s)
duration = date_first - date_second
miles = second[1][1] - first[1][1]
miles_per_gallon = miles / first[1][0]
p “The #{first[1][0]} gallons of gas purchased on
#{date_first.strftime(’%m/%d/%Y’)} lasted #{duration.to_i} days. The
mileage was #{miles_per_gallon} miles per gallon.”
end

The key here is the each_cons coming from the enumerable mixin, which
iterates the array in pairs of twos.

Brilliant. That enumerator mixin is crazy awesome. Thanks.

Disclaimer: I am a German living in Australia, so if I got the date
format or the miles per gallon calculation wrong, blame the non-metric
system.

Max