Created
May 6, 2011 23:45
-
-
Save vanpelt/960018 to your computer and use it in GitHub Desktop.
The Universe... in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Matter | |
| attr_accessor :position, :mass | |
| def initialize(position, mass) | |
| @position = position | |
| @mass = mass | |
| end | |
| def <=> other_matter | |
| @distance <=> other_matter.distance | |
| end | |
| end | |
| class Star < Matter | |
| def initialize(mass) | |
| super(0, mass) | |
| end | |
| end | |
| class Planet < Matter | |
| attr_accessor :moons | |
| def initialize(position, mass, moons = []) | |
| @moons = moons | |
| super(position, mass) | |
| end | |
| def mass | |
| @mass + @moons.inject(0) do |mass, moon| | |
| mass + moon.mass | |
| end | |
| end | |
| end | |
| class Moon < Matter | |
| attr_accessor :planet | |
| def initialize(position, mass, planet = nil) | |
| @planet = planet | |
| super(position, mass) | |
| @planet.moons << self if planet | |
| end | |
| end | |
| class PlanetarySystem | |
| def initialize(star) | |
| @star = star | |
| @planets = [] | |
| end | |
| def <<(planet) | |
| @planets << planet | |
| end | |
| def each(&block) | |
| @planets.sort.each &block | |
| end | |
| def to_a | |
| self.map {|p| p } | |
| end | |
| def planetary_mass | |
| @planets.inject(0) do |mass, matter| | |
| mass + matter.mass | |
| end | |
| end | |
| end | |
| sun = Star.new(1.9891e+30) | |
| solar_system = PlanetarySystem.new(sun) | |
| earth = Planet.new(149_597_890, 5.9742e+23) | |
| solar_system << earth | |
| moon = Moon.new(384_399, 8.94e+22, earth) | |
| venus = Planet.new(108_208_930, 4.8690e+24) | |
| solar_system << venus | |
| mars = Planet.new(227_936_640, 6.41913+23) | |
| solar_system.planetary_mass.should == 486127859 | |
| (venus > earth).should == false | |
| (mars > earth).should == true | |
| solar_system.map do |planet| | |
| planet.distance | |
| end.should == [227_936_640, 149_597_890, 108_208_930, 0] | |
| solar_system.to_a.should == [mars, earth, venus, sun] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment