Ruby 块和 Lambda
发布: (2025年12月31日 GMT+8 12:42)
2 min read
原文: Dev.to
Source: Dev.to
Ruby 블록(Block)
Ruby的块(Block)是一种在方法调用时传递代码块的方式。
def call_block
puts 'Start of method'
yield
yield
puts 'End of method'
end
call_block { puts 'In the block' }
块也可以接受参数。
def call_block
yield('hello', 99)
end
call_block { |str, num| puts str + ' ' + num.to_s }
可以使用 block_given? 检查块是否存在。
def try
if block_given?
yield
else
puts "no block"
end
end
try # => "no block"
try { puts "hello" } # => "hello"
try do puts "hello" end # => "hello"
块内部使用的变量拥有独立于块外部的作用域。
x = 10
5.times do |x|
puts "x inside the block: #{x}"
end
puts "x outside the block: #{x}"
Lambda
Lambda 是创建匿名函数的方法,使用 lambda 或 -> 定义。
prc = lambda { puts 'Hello' }
prc.call
多行 Lambda
toast = lambda do
'Cheers'
end
puts toast.call
Lambda 也可以作为参数传递给方法。
def some_mtd(some_proc)
puts 'Start of mtd'
some_proc.call
puts 'End of mtd'
end
say = lambda do
puts 'Hello'
end
some_mtd(say)
接受参数的 Lambda 示例:
a_Block = lambda { |x| "Hello #{x}!" }
puts a_Block.call('World') # => "Hello World!"