rails中yield的用法
yield是与ruby中的block紧密结合的,block的语法就是{}(单行)或者do…end(多行)
一个block总是被一个具有相同名称的函数调用,这就是说如果你有个名为test的block,你就可以使用名为test的函数来调用这个block.
yield语法的一个例子:
def test
puts "You are in the method"
yield
puts "You are again back to the method"
yield
end
test {puts "You are in the block"}
打印结果:
You are in the method
You are in the block
You are again back to the method
You are in the block
这样当执行test方法时,yield会去查找并调用名称为test的block
当然yield后面也可以有参数
def test
yield(2)
end
test {|i| puts "This index is #{i}"}
打印结果:
This index is 2
也可以传多个参数如:
yield(a,b)
test{|a,b| puts "#{x}, #{y}"}
另一种写法:
def test(&block)
block.call
end
test { puts "Hello World!"}
调用block的两种方式:
1.单行block: test { .... }
2.多行block:
test do
....
end
查看评论...