在Ruby中,Lambda表达式是一种轻量级的匿名函数,可以像普通函数一样进行调用。它们通常用于传递代码块或作为参数传递给其他方法。Lambda表达式的语法如下:
lambda { |参数| 函数体 }
或者使用->符号:
->(参数) { 函数体 }
以下是一些使用Lambda表达式的示例:
square = ->(x) { x * x }
puts square.call(5) # 输出:25
def apply_operation(operation, a, b)
operation.call(a, b)
end
add = ->(a, b) { a + b }
multiply = ->(a, b) { a * b }
puts apply_operation(add, 3, 4) # 输出:7
puts apply_operation(multiply, 3, 4) # 输出:12
numbers = [1, 2, 3, 4, 5]
squares = numbers.map { |x| x * x }
puts squares.inspect # 输出:[1, 4, 9, 16, 25]
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = numbers.select { |x| x.even? }
puts even_numbers.inspect # 输出:[2, 4, 6, 8, 10]
people = [
{ name: "Alice", age: 30 },
{ name: "Bob", age: 25 },
{ name: "Charlie", age: 35 }
]
sorted_people = people.sort_by { |person| person[:age] }
puts sorted_people.inspect
# 输出:[{:name=>"Bob", :age=>25}, {:name=>"Alice", :age=>30}, {:name=>"Charlie", :age=>35}]
这些示例展示了如何在Ruby中使用Lambda表达式。Lambda表达式是一种强大的工具,可以帮助您编写更简洁、灵活的代码。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。