gpt4 book ai didi

一行中的 Ruby 赋值和比较?

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

这似乎没有按预期工作:

if c = Countries.first.nil?
... do something
end

比较有效但赋值无效。有没有办法在一行中同时进行比较和赋值?

最佳答案

这才是你真正想要的:

if (c = Countries.first).nil?
# ... do something
end

在您的示例中,您将得到 c = (Countries.first.nil?),因此 c 将为 false

你实际上可以这样写:

unless (c = Countries.first)
# ... do something
end

但要小心!我会保留 () ,否则它会看起来像你的意思是比较,并且 ruby​​ 解释器会警告你。

我有时会使用这种模式,但很少使用它,因为它让事情变得不那么清晰。

关于一行中的 Ruby 赋值和比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3835170/

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