Created
August 2, 2014 19:27
-
-
Save domgetter/a039ff62dcaa60ff52e9 to your computer and use it in GitHub Desktop.
enum with select to return custom collection
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 CoolCollection | |
include Enumerable | |
def initialize | |
@elements = [] | |
end | |
def <<(elem) | |
@elements << elem | |
end | |
def each &block | |
@elements.each do |elem| | |
if block_given? | |
block.call elem | |
else | |
yield elem | |
end | |
end | |
end | |
def select &block | |
selection = @elements.select do |elem| | |
if block_given? | |
block.call elem | |
else | |
yield elem | |
end | |
end | |
output = self.class.new | |
selection.each do |elem| | |
output << elem | |
end | |
output | |
end | |
end | |
my_coll = CoolCollection.new | |
my_coll << 7 | |
my_coll << 9 | |
p my_coll | |
#=> #<CoolCollection:0x25cad78 @elements=[7, 9]> | |
my_coll.each {|elem| puts elem} | |
selection = my_coll.select {|elem| elem == 7} | |
p selection | |
#<CoolCollection:0x25c9e48 @elements=[7]> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment