您的位置:首页 > 编程语言 > Ruby

[2014年学习计划之RoR系列] 第二步 – 熟悉Ruby语言 (2/n) Blocks and Iterators (代码块和迭代器)

2014-01-14 14:14 323 查看
[就算没有含金量,也请尊重原创, 转载自我的独立博客http://brucejia.net]

 

Blocks and Iterators (代码块和迭代器)

代码块和迭代器是Ruby语言中比较有特点的东西。先看代码块吧,如下面代码所示,代码块通常是由大括号({和}) 或者do/end包起来的一段代码。

1: { puts "Hello" } # this is a block

2: do ###

3:     club.enroll(person) # and so is this

4:     person.socialize #

5: end ###


建议:单行的block用大括号;多行的block用do/end

 

blocks可以用来实现回调函数和迭代器。

1: def call_block

2:     puts "Start of method"

3:     yield

4:     yield

5:     puts "End of method"

6: end

7: 

8: call_block { puts "In the block" }


 

注意代码中的yield关键字。上边的代码产生结果如下:

Start of method

In the block

In the block

End of method

yield会调用跟方法(method)相关联的block,可以调用一次或多次。

当然block也可以带有自己的参数

1: call_block {|str, num| ... }


调用的时候将参数传入给yield就好了。 - 这个时候yield看起来像个函数了。

1: def call_block

2:     yield("hello", 99)

3: end


动手试试看这两行代码会输出什么。

1: animals = %w( ant bee cat dog elk ) # create an array

2: animals.each {|animal| puts animal } # iterate over the contents
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ruby on rails ruby