Created
February 10, 2014 13:25
-
-
Save jasoares/8915891 to your computer and use it in GitHub Desktop.
Sample of ruby yield methods, modules and includes...
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 Array | |
def each_valid | |
self.each do |val| | |
valid = yield val | |
puts val if valid | |
end | |
end | |
def map | |
internal_array = [] | |
self.each do |val| | |
internal_array << yield(val) if block_given? | |
end | |
internal_array | |
end | |
def map_tuple | |
internal_array = [] | |
prev = nil | |
self.each do |val| | |
internal_array << yield(prev, val) if block_given? | |
prev = val | |
end | |
internal_array | |
end | |
end | |
module IterateHelpers | |
def each_valid | |
self.each do |val| | |
valid = yield val | |
puts val if valid | |
end | |
end | |
end | |
class Stand | |
include Enumerable | |
include IterateHelpers | |
attr_accessor :cars | |
def initialize(cars) | |
@cars = cars | |
end | |
def cars | |
@cars | |
end | |
def each | |
cars.each do |car| | |
yield car | |
end | |
end | |
def cars=(cars) | |
self.cars = cars | |
end | |
end | |
class Car | |
include Enumerable | |
def <=>(other) | |
return 1 if car.horse_power > other.horse_power | |
return -1 if car.horse_power < other.horse_power | |
0 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment