当前位置: 首页 > 工具软件 > Ruby-Guard > 使用案例 >

Amazing ruby: block & yield

高墨一
2023-12-01

之前听Anand讲用了ruby以后就不想用java了,如今看来还真是。Ruby里面有好多神奇的function,先小记一下block&yield


简单来说,ruby允许把一整个statement以parameter的形式放在block中传递,目标method通过yield运行这些statement.

基本用法,Eg.

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

block中的command也允许有一到多个参数存在
test {|a, b| statement}

yield a, b

更多见tutorial: http://www.tutorialspoint.com/ruby/ruby_blocks.htm

 类似资料: