At the begin of studying Ruby,I knew that you can write the following codes to print an object 3 times:
3.times {print "*"}
or print the number from 1 to 6 like this:
1.upto(6) {|i| print i}
I thought these are fixed formats and I didn't know the reason of these before this afternoon.In fact,these formats are called Blocks in Ruby."times" and "upto" are functions of the "3" and "1" objects.The following braces and sentances are defining a block and passed to these function.In these functions it use "yield" to call these blocks which were passed.Then the codes of times maybe like this:
def times
while condition
yield
end
end
and the codes of upto function maybe like this:
def upto(num)
a loop
yield(i) #there is a parameter when you call yield and pass to the block.
end loop
end
Of cause,the really codes of these functions are not so simply.
The "yield" keywork and Blocks can implement a pattern called a "Template Pattern or Strategy Pattern" in Java.You can implement the same codes in a function and pass the difference codes by Blocks.
By the way,you can use two braces to single-line Blocks or "do...end" to define multiline Blocks.
3.times {print "*"}
or print the number from 1 to 6 like this:
1.upto(6) {|i| print i}
I thought these are fixed formats and I didn't know the reason of these before this afternoon.In fact,these formats are called Blocks in Ruby."times" and "upto" are functions of the "3" and "1" objects.The following braces and sentances are defining a block and passed to these function.In these functions it use "yield" to call these blocks which were passed.Then the codes of times maybe like this:
def times
while condition
yield
end
end
and the codes of upto function maybe like this:
def upto(num)
a loop
yield(i) #there is a parameter when you call yield and pass to the block.
end loop
end
Of cause,the really codes of these functions are not so simply.
The "yield" keywork and Blocks can implement a pattern called a "Template Pattern or Strategy Pattern" in Java.You can implement the same codes in a function and pass the difference codes by Blocks.
By the way,you can use two braces to single-line Blocks or "do...end" to define multiline Blocks.