Created
October 3, 2016 18:36
-
-
Save russolsen/2ac25623ff1d0c7f6fcb946129bfc030 to your computer and use it in GitHub Desktop.
Demo that in Ruby the for expression is just sugar around a call to the each method.
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
# Demo that for calls each | |
class ThreeOf | |
def initialize(value) | |
@value = value | |
end | |
def each(&block) | |
block.call(@value) | |
block.call(@value) | |
block.call(@value) | |
end | |
end | |
collection = ThreeOf.new(99) | |
for i in collection | |
puts i | |
end | |
puts "=======" | |
collection.each {|i| puts i} | |
# And if that doesn't convince you... | |
class Array | |
alias_method :orig_each, :each | |
def each(*args, &block) | |
puts "Array Each called!" | |
orig_each(*args, &block) | |
end | |
end | |
puts "=======" | |
puts "For loop with array" | |
for i in [1,2,3] | |
puts i | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment