Skip to content

Instantly share code, notes, and snippets.

@kirel
Created August 20, 2008 17:24
Show Gist options
  • Save kirel/6407 to your computer and use it in GitHub Desktop.
Save kirel/6407 to your computer and use it in GitHub Desktop.
class Distance
FACTORS = {
:kilometers => 1000.0,
:meters => 1.0,
:decimeters => 0.1,
:centimeters => 0.01,
:millimeters => 0.001,
}
UNITS = FACTORS.keys
### class methods for converting
def self.convert(value, from_unit, to_unit = :meters)
value * FACTORS[unit] / FACTORS[otherunit]
end
class << self
# convert everything
UNITS.each do |to_unit|
UNITS.each do |from_unit|
define_method "#{from_unit}_to_#{to_unit}" do |value|
convert(value, from_unit, to_unit)
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment