ruby的方法和block

作者: 孤独的猫
发布时间:2015-07-13 11:31:25

在ruby中方法与block的合用

:~/ruby$ irb
irb(main):001:0> def take_block(p1)
irb(main):002:1>   if block_given?
irb(main):003:2>      yield(p1)
irb(main):004:2>   else
irb(main):005:2*      p1
irb(main):006:2>   end
irb(main):007:1> end
=> nil
irb(main):008:0> take_block("no block")
=> "no block"
irb(main):009:0> take_block("no block") {|s| s.sub(/no /,'')}
=> "block"
irb(main):010:0>

 

下面是调用yield实现的简单迭代(回调)

irb(main):001:0> def three_times
irb(main):002:1>    yield
irb(main):003:1>    yield
irb(main):004:1>    yield
irb(main):005:1> end
=> nil
irb(main):006:0> three_times { puts "Hello"}
Hello
Hello
Hello
=> nil
irb(main):007:0>

 

注:

    Kernel.block_given?方法: 当某方法和block关联在一起时, Kernel.block_given?返回真,否则返回假





标签: Ruby
来源:http://www.cnblogs.com/djcsch2001/archive/2012/03/24/2415936

推荐: