【问题标题】:Ternary Operator Outputting True Option when False三元运算符在假时输出真选项
【发布时间】: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


【解决方案1】:

最安全的做法是在输出变量时进行检查。在打印最后一行之前,您可以简单地向下移动三进制。

我很想将它提取到一个单独的方法中。事实上,这就是 Rails 对pluralize 所做的事情。我们可以创建自己的简化版本:

def pluralize(count, noun)
  "#{count} #{count==1 ? noun : noun + 's'}"
end

那么您的代码可能如下所示:

99.downto(1) do |n|
  puts "#{pluralize(n, "bottle")} of beer on the wall, #{pluralize(n, "bottle")} of beer."
  puts "Take one down and pass it around, #{pluralize(n-1, "bottle")} of beer on the wall."
end

【讨论】:

  • 哎呀!使用.downto 和自定义方法更简洁,谢谢!
【解决方案2】:

beer_bottles -= 1 更新后,您不再计算 plural_or_singular,因为 beer_bottles 已更新。

解决办法:

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
  plural_or_singular = beer_bottles > 1 ? plural : singular
  puts "BOTTLE COUNT: #{beer_bottles}"

  puts "Take one down and pass it around, #{beer_bottles} #{plural_or_singular} of beer on the wall."
end

【讨论】:

  • 现在完全不需要第一次检查了。
  • 啊,是的!出于某种原因,我假设每次插值时都会计算plural_or_singular。哎呀!谢谢马克!
猜你喜欢
  • 2014-08-03
  • 2018-04-22
  • 1970-01-01
  • 1970-01-01
  • 2013-05-17
  • 2016-07-02
  • 1970-01-01
  • 2014-02-19
  • 1970-01-01
相关资源
最近更新 更多