Blocks in Ruby

本文介绍了Ruby语言中Block的使用方式及其背后的原理。通过具体示例解释了如何使用Block来实现多次打印字符和递增打印数字的功能,并探讨了Block与函数内部yield关键字之间的关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值