Ruby:块

2018-01-19  本文已影响0人  Wougle

首先来看一下块的语法

block_name{
   statement1
   statement2
   ..........
}

块的调用方法一般采用以下形式:

对象.方法名(参数列表)|块变量|
    块代码
end
#或者
对象.方法名(参数列表){|块变量|  
    块代码
}

再来看一下块的回调

1.yield

yield 主要用于隐式 block 回调,ruby 方法默认可以不声明 block,在其内部可通过 yield 回调。

def test
    yield("YJ") if block_given? # block_given?判断是否存在 block
end

test{|str| puts str}
2.Call

如果方法的最后一个参数前带有 &,那么可以向该方法传递一个块,且这个块可被赋给最后一个参数。如果 * 和 & 同时出现在参数列表中,& 应放在后面。block 的参数使用 call 回调。

def test(&block)
    block.call("YJ") if block
end

test{|str| puts str}
3.Proc

如果需要传入多个block,可以利用Proc将block转换为属性

def test(block1, block2)
    block1.call("W") if block1
    block2.call("G") if block1
end

block1 = Proc.new do |str|
    puts str
end

block2 = Proc.new{|str|
    puts str
}

test(block1, block2) # 传入 block 临时变量
上一篇 下一篇

猜你喜欢

热点阅读