The key word 'yield' is the core of Iterators, So I use a Iterators to clarify the 'yield'
class Sequence include Enumerable def initialize(from, to, by) @from, @to, @by = from, to, by end def each x = @from y = @by while x<= @to yield x #We will do something to the x, but not now, the operation will ensure in the following block. x += @by end end end
We have use the 'yield' to possess the code line, but have not define the actual operationThen, we can use block to take the place!
s = Sequence.new(1, 10 , 2)
s.each {|a| print a} #The |a| means use 'a' to alias the 'x''s place, then use 'print' to take the 'yield''s place
So the result is:13579
If we use bellow codes
s = Sequence.new(1, 10 , 2)
s.each {print 1} #Nothing will alias to x, but the 'print 1' will take the 'yield''s place
So, the result would be:
11111