gpt4 book ai didi

ruby - 为什么这个 Ruby 'if' 没有按预期运行?

转载 作者:太空宇宙 更新时间:2023-11-03 17:02:04 26 4
gpt4 key购买 nike

我确定我在这里遗漏了一些东西,但仍然如此。

foo['bar'] = nil

if(foo['bar'] == nil)
puts "foo bar is nil :("

然而,没有任何反应?有什么想法吗?

最佳答案

您需要一个end 语句来关闭您的if

if(foo['bar'] == nil)
puts "foo bar is nil :("
end

请注意,有一个 nil? 方法用于检查是否为 nil 并且您的条件周围的括号不是必需的,因此编写起来更符合 Ruby 的习惯:

if foo['bar'].nil?
puts "foo bar is nil :("
end

作为Arkku注释掉,一行if可以简洁的写成:

puts "foo bar is nil :(" if foo['bar'].nil?

哪个更好取决于上下文(例如,您想强调条件还是强调条件为真时会发生什么)和一定程度的个人偏好。但作为示例,您可以在方法的开头放置一个保护条件,例如

raise "bar needed" if foo['bar'].nil?

关于ruby - 为什么这个 Ruby 'if' 没有按预期运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2559490/

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