Last active
August 29, 2015 14:00
-
-
Save glebm/11230676 to your computer and use it in GitHub Desktop.
make all Ruby things Enumerable
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 Object | |
def each(&block) | |
return to_enum(:each) { 1 } unless block | |
[self].each(&block) | |
end | |
include Enumerable | |
end | |
class NilClass | |
def each(&block) | |
return to_enum(:each) { 0 } unless block | |
end | |
end | |
#--- | |
def greetings(users) | |
users.map { |user| "Hello, #{user}" } | |
end | |
greetings %w(Finn Jake) #=> ["Hello, Finn", "Hello, Jake"] | |
greetings 'Finn' #=> ["Hello, Finn"] | |
greetings nil #=> nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment