#############################################################################
# title: erlang_program_in_ruby.rb
# desc: translation of erlang_program.prompt.erl to ruby
# author: gianna fusaro
# date: october 20, 2015
#############################################################################
# WeightItem: item with label, weight, and unit
class WeightItem
LBS_PER_KG = 0.45359237
attr_reader :label, :unit
def initialize(item)
@label, @unit, @weight = item
end
# force weight to float
def weight
@weight.to_f
end
# convert weight from lbs to kg, or kg to kg
def to_kg
case @unit
when 'l' then WeightItem.new [@label, 'k', weight*LBS_PER_KG]
when 'k' then self
else fail "unsupported conversion from #{@unit} to kilograms"
end
end
def to_s
"#{@label.ljust(14)} #{weight} #{@unit}"
end
end
# KWeightItemCollection: collection of WeightItems in kg
class KWeightItemCollection
def initialize(items)
@items = items.map { |item| WeightItem.new(item).to_kg }
end
# returns items with min and max weight
def minmax
@items.minmax { |a, b| a.weight <=> b.weight }
end
# print each item in kg
# print item information for max and min weights
def summarize
@items.each { |item| puts item }
min, max = minmax
puts "Max weight was #{max.weight} #{max.unit} in #{max.label}"
puts "Min weight was #{min.weight} #{min.unit} in #{min.label}"
end
end
# handle user input
unless ARGV.empty?
# parse arguments and display summary
inputs = ARGV.collect { |arg| arg.split }
KWeightItemCollection.new(inputs).summarize
else
# display usage information
puts <<-END
Usage: erlang_program_in_ruby.rb \
'name1 unit1 value1' 'name2 unit2 value2' ... \n\
Example: erlang_program_in_ruby.rb 'Penny l 0.00551156' 'Dime l 0.005004493'
END
end