在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?返回真,否则返回假