Skip to content

Instantly share code, notes, and snippets.

@blaix
Last active August 18, 2020 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blaix/b50a4629b766687516afeb1aac3ee789 to your computer and use it in GitHub Desktop.
Save blaix/b50a4629b766687516afeb1aac3ee789 to your computer and use it in GitHub Desktop.
module Stomach
def eat(food)
@contents ||= []
@contents << food
end
def vomit
@contents.pop
end
end
class Lifeform
attr_reader :dna
def initialize(dna = [])
@dna = dna
end
def reproduce(other = nil)
return clone unless other
new_dna = dna.zip(other.dna).flatten
self.class.new(new_dna)
end
end
class Person < Lifeform
# Person can inherit from lifeform which makes sense
# because all persons are lifeforms, but can also
# gain stomach features (not shared by all lifeforms)
# by including a module. As opposed to putting stomach
# features into a base class. Requiring all stomach-havers
# to inherit from that, and almost definitely ending up
# with a bunch of other stuff you don't need or want
# as the base class bloats because you've muddied the hierarchy.
include Stomach
end
p = Person.new
p.eat("hot dog") # => ["hot dog"]
p.vomit # => "hot dog"
p.reproduce # => #<Person:...>
p1 = Person([1, 2])
p2 = Person([3, 4])
p1.reproduce(p2).dna # => [1, 3, 2, 4]
@beck
Copy link

beck commented Aug 18, 2020

Or if you're David Blaine:

def magic_vomit
    @contents.shift
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment