Skip to content

Instantly share code, notes, and snippets.

@StasKoval
Forked from jensendarren/enumerable_example.rb
Created December 30, 2015 18:19
Show Gist options
  • Save StasKoval/416ef988b6e49deba20b to your computer and use it in GitHub Desktop.
Save StasKoval/416ef988b6e49deba20b to your computer and use it in GitHub Desktop.
See rotati blog post
class Coffee
attr_accessor :name
attr_accessor :strength
def initialize(name, strength)
@name = name
@strength = strength
end
def <=>(other_coffee)
self.strength <=> other_coffee.strength
end
def to_s
"<name: #{name}, strength: #{strength}>"
end
end
class CoffeeShop
include Enumerable
attr_accessor :coffees
def initialize(*coffees)
@coffees = coffees
end
def each
@coffees.map{|coffee| yield coffee}
end
end
laos = Coffee.new("Laos", 10)
angkor = Coffee.new("Angkor", 7)
nescafe = Coffee.new("Nescafe", 1)
my_favorite_coffee = [laos, angkor, nescafe]
puts "Sorting with array: #{my_favorite_coffee.sort}"
puts "Our arrays strongest Coffee sir! #{my_favorite_coffee.max}"
puts
cs = CoffeeShop.new(nescafe, laos, angkor)
puts "Sorting with CoffeeShop and Enumerable #{cs.sort}"
puts "Our shops strongest Coffee sir! #{cs.max}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment