module UnitConvert
Constants
- CONVERSIONS
Public Instance Methods
Source
# File lib/unit_convert.rb, line 31 def convert(amount:, from:, to:) from = from.to_s.downcase to = to.to_s.downcase return { error: usage_message } if from.empty? || to.empty? if temperature?(from) && temperature?(to) return { value: convert_temperature(amount, from, to) } end factor = CONVERSIONS[[from, to]] return { error: "Cannot convert #{from} to #{to}" } unless factor { value: amount * factor } end
Source
# File lib/unit_convert.rb, line 50 def convert_temperature(amount, from, to) from = from.downcase to = to.downcase celsius = case from when "c" then amount when "f" then (amount - 32) * 5.0 / 9.0 when "k" then amount - 273.15 end case to when "c" then celsius when "f" then (celsius * 9.0 / 5.0) + 32 when "k" then celsius + 273.15 end end
Source
# File lib/unit_convert.rb, line 66 def format_result(amount:, from:, to:, value:) rounded = value.is_a?(Float) ? value.round(4) : value "#{amount} #{from} = #{rounded} #{to}" end
Source
# File lib/unit_convert.rb, line 19 def parse_command(text) parts = text.to_s.strip.split(/\s+/) return { error: usage_message } if parts.length < 3 amount = parts[0].to_f return { error: usage_message } if parts[0] !~ /\A-?\d+(?:\.\d+)?\z/ from = parts[1].downcase to = parts[2].downcase { amount: amount, from: from, to: to } end
Source
# File lib/unit_convert.rb, line 46 def temperature?(unit) %w[c f k].include?(unit.to_s.downcase) end
Source
# File lib/unit_convert.rb, line 15 def usage_message "Usage: !convert <amount> <from> <to> — e.g. !convert 100 km mi, !convert 25 c f" end