How can I convert a Collection from One type to another in Ruby.
I have a collection MileageRecords(Date, Odometer, Gallons) and would like to generate a li开发者_JAVA技巧st of FooObject(Miles, MPG). The FooObject properties are calculated from the Mileage record.
This gets me the data, but I don't see how to create a collection
LogEntry.all.each_with_index do |log, index|
if index > 0
miles = LogEntry.all[index - 1].odometer - log.odometer
mpg = miles / log.gallons
puts "#{log.date} #{miles} #{mpg}"
end
end
You can't do any sort of implicit type casting, especially with your own classes. The best method is probably to create a to_foo_object
method for MileageRecords
class MileageRecords
def to_foo_object
FooObject.new(miles, mpg) # you'll need to define these variables somehow
end
end
Then you can call
mileage_records.map{|mr| mr.to_foo_object }
or to shorten it up a bit
mileage_records.map(&:to_foo_object)
How about:
fuel_economy = LogEntry.all.each_cons(2).map do |prev, curr|
miles = curr.odometer - prev.odometer
mpg = miles / curr.gallons
FuelEconomy.new(miles, mpg)
end
精彩评论