【发布时间】:2017-09-18 22:40:01
【问题描述】:
下面的程序输出歌曲“99瓶啤酒”的歌词。
当歌曲到达只剩下 1 个瓶子的地步时,它使用“瓶子”的单数形式。为了适应这一点,我使用了三元运算符在任何给定时刻选择正确的情况。
但是,当我的程序中的beer_bottles 计数达到 1 时,最后一句仍然输出“bottles”,即使很明显三元运算符的计算结果为 false。
我在 IRB 中使用beer_bottles = 1 测试了三元运算符,它正确输出了错误选项:“bottle”。
非常感谢帮助理解为什么会发生这种情况!
beer_bottles = 99
while beer_bottles >= 2 do
plural = "bottles"
singular = "bottle"
plural_or_singular = beer_bottles > 1 ? plural : singular
puts "#{beer_bottles} #{plural_or_singular} of beer on the wall, #{beer_bottles} #{plural_or_singular} of beer."
beer_bottles -= 1
puts "BOTTLE COUNT: #{beer_bottles}"
puts "Take one down and pass it around, #{beer_bottles} #{plural_or_singular} of beer on the wall."
end
【问题讨论】:
-
问:你确定你当时真的降到了“1”吗?问:你应该在减量AFTER之后移动三元吗?
-
您在 2 处停止 while 循环。减去 1 后,您不会重新计算
plural_or_singular。你应该把它往下移。
标签: ruby ternary-operator string-interpolation