Ruby Base 之代码块、迭代子和过程对象
在Ruby中一切皆对象。甚至一个代码块也是一个对象!在Ruby中,代码对象被称为代码块。你可以把代码块想像成小的程序单元。它们包含Ruby代码并且能够在执行它们时转入到方法中。在Python,C和Java中与之类似的概念是函数指针,匿名函数,内部类和回调函数。
Ruby代码块的语法是,把Ruby代码放在大括号之间或放在do/end命令之间。如下所示:
{#这是一个代码块...}
do#...并且这也是一个代码块end
def someMethodyieldend
irb(main):001:0> someMethod {puts "hello world"}hello world
irb(main):001:0> def fibonacci (stop)while stop < 20stop=yieldendend=> nilirb(main):006:0> i=0; j=1; fibonacci(j) {puts i; temp = i; i = j;j = temp + j}0112358
irb(main):031:0> barnYard = [Cow.new, Duck.new, Chicken.new, Horse.new, Dog.new]=> [#<Cow:0x58d2f48>, #<Duck:0x58d2f30>, #<Chicken:0x58d2f00>, #<Horse:0x58d2ee8>, #<Dog:0x58d2ed0>]irb(main):032:0> barnYard.each {|animal| animal.talk}MoooooQuackCluck-cluckNaaaayBark bark
irb(main):001:0> 3.times {puts "Ruby is cool!"}Ruby is cool!Ruby is cool!Ruby is cool!
irb(main):003:0> simpleProc.callhello=> nilirb(main):004:0> anotherProc.call("hello yourself")hello yourself=> nil
irb(main):001:0> def simpleMethod(aProc)puts "Is Ruby cool or what?"aProc.call("Way cool dude!")end=> nilirb(main):005:0> simpleMethod(anotherProc)