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!"
Back to Blog

相关文章

阅读更多 »

我为什么在学习西班牙语?

我为什么继续学习西班牙语?人们经常问我:“你为什么在学习西班牙语?”这有点奇怪,因为我真的不知道到底是什么…

Zephyr 在 Arduino UNO Q MCU 上

概述 Arduino UNO Q 使用 STM32U585 MCU 来处理所有 Arduino 功能。它与主处理器以及板上的 GPIO 引脚进行通信。板载的...

副项目与 AI

Side Projects 和 AI 的封面图片 https://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s...