gpt4 book ai didi

ruby - 你会如何在 Ruby 中表达成语 "with this object, if it exists, do this"?

转载 作者:数据小太阳 更新时间:2023-10-29 07:12:10 24 4
gpt4 key购买 nike

在 Ruby(尤其是 Rails)中,您经常需要检查某物是否存在,然后对其执行操作,例如:

if @objects.any?
puts "We have these objects:"
@objects.each { |o| puts "hello: #{o}"
end

这是最短的,一切都很好,但是如果你有 @objects.some_association.something.hit_database.process 而不是 @objects 呢?我将不得不在 if 表达式中重复两次,如果我不知道实现细节并且方法调用很昂贵怎么办?

显而易见的选择是创建一个变量,然后测试它,然后处理它,但是你必须想出一个变量名(呃),它也会在内存中徘徊,直到范围结束。

为什么不是这样的:

@objects.some_association.something.hit_database.process.with :any? do |objects|
puts "We have these objects:"
objects.each { ... }
end

你会怎么做?

最佳答案

请注意,如果您只打算发送 each,则没有理由检查数组是否至少有一个带有 any? 的元素,因为发送 每个到一个空数组是一个空操作。

要回答您的问题,也许您正在寻找 https://github.com/raganwald/andand

关于ruby - 你会如何在 Ruby 中表达成语 "with this object, if it exists, do this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13828700/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com