ruby块:
- 块中的代码总是包含在大括号{}中
- 块总是从与其具有相同名称的函数调用,eg:如果你的块名为
test
,那么你要使用函数test来调用这个块。 - 你可以使用
yield
来调用块
yield语句
1、基本用法
def test
puts "在test方法内"
yield
end
test {puts "你在块内"}
2、带参数的用法
传递有参数的yield语句
def test
puts "在test方法内"
yield 1
end
test { | i | puts "你在块#{i}内"}
yield后面跟着参数,可以传多个参数。
- 使用
&block
方法的最后一个参数带有&block
,可以向该方法传递一个块。
def test(&block)
block.call
end
test{puts 'hello world'}
def test(a, b, &block)
block.call a, b
end
test{puts 'hello world'}
4.检查是否有代码块被传入
def test
if block_given?
yield
else
puts 'no block'
end
end
test //未传入代码块
test{puts "a block"} //传入代码块
网友评论