Ruby 匿名函数

编程/开发
481
0
0
2022-06-03

yield用法

在方法中使用yield来执行匿名函数
def call_block
    puts "start" 
    yield 
    yield
    puts "end"
end
# call_block {puts "blocks is cool"}
call_block do
    puts "blocks is cool"
end
带参数的code block
def call_block 
    yield(1)
    yield("jelly")
end

call_blcok do |x|
puts "#{x} hello"
end
将匿名函数转成类
def call_block(&block)
  block.call(1)
  block.call(2)
end

call_block do |x|
    puts "#{x}: cool"
end