space_age.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# Calculate how old someone is in terms of a given planet's solar years.
class SpaceAge
  # One Earth year, in seconds
  EARTH_YEAR = 31_557_600

  # Orbital periods of each planet, in Earth years
  ORBITS = {
    mercury: 0.2408467,
    venus:   0.61519726,
    earth:   1.0,
    mars:    1.8808158,
    jupiter: 11.862615,
    saturn:  29.447498,
    uranus:  84.016846,
    neptune: 164.79132
  }.freeze

  # Dynamically define a method for each planet
  ORBITS.each do |planet, orbit|
    define_method "on_#{planet}" do
      years(orbit)
    end
  end

  def initialize(seconds)
    @seconds = seconds
  end

  attr_reader :seconds

  private

  def years(orbital_period)
    (@seconds / (EARTH_YEAR * orbital_period)).round(2)
  end
end

@alialliallie thinks this looks great

Comments


You're not logged in right now. Please login via GitHub to comment