【问题标题】:Skipping until statement at certain number跳过直到特定数量的语句
【发布时间】:2017-08-12 10:09:02
【问题描述】:

我有一种方法可以在墙上唱出“啤酒瓶”。我有一个问题,当它达到“1”时,我希望瓶子是单数而不是复数。

我设法通过创建一个“if”来做到这一点。当@bottles 达到1 这有效。但是,当 until 语句达到 1 时,它会说

'Take one down, pass one round
one bottles of beer'

此时我需要 until 语句来跳过它。这是怎么做到的?

'

 class BeerSong

  require 'humanize'

  attr_accessor :bottles

  def initialize(bottles)
  @bottles = bottles
  @bottles = 0 if @bottles < 0
  @bottles = 99 if @bottles > 99
  end

  public

  def print_song
  until @bottles == 0 do
   break if @bottles == 0
   puts "#{@bottles.humanize} bottles of beer on the wall"
   puts "#{@bottles.humanize} bottles of beer"
   puts "Take one down, pass one round"
   puts "#{(@bottles - 1).humanize} bottles of beer"
   @bottles = @bottles - 1
     if @bottles == 1
     puts "#{@bottle} bottle of beer on the wall"
     puts "#{@bottles.humanize} bottle of beer"
     puts "Take one down, pass one round"
     puts "#{(@bottles - 1).humanize} bottles of beer"
     @bottles = @bottles - 1
     end
    end
  end
end


beer = BeerSong.new(99)
beer.print_song

【问题讨论】:

    标签: ruby


    【解决方案1】:

    你需要做一个if/else,所以它只会在@bottles - 1 == 1时打印歌曲的单数形式,像这样:

    def print_song
      until @bottles == 0 do
        puts "#{@bottles.humanize} bottles of beer on the wall"
        puts "#{@bottles.humanize} bottles of beer"
        puts "Take one down, pass one round"
    
        if @bottles - 1 == 1
          puts "#{(@bottles - 1).humanize} bottle of beer"
        else
          puts "#{(@bottles - 1).humanize} bottles of beer"
        end
    
        @bottles = @bottles - 1
    
        if @bottles == 1
          puts "#{@bottle} bottle of beer on the wall"
          puts "#{@bottles.humanize} bottle of beer"
          puts "Take one down, pass one round"
          puts "#{(@bottles - 1).humanize} bottles of beer"
          @bottles = @bottles - 1
        end
      end
    end
    

    虽然 pluralsingular 不需要重复整首歌曲,但您可以使用变量并更改它(就像使用 @bottles ) 例如,当您到达1 时,print_song 可能是:

    def print_song
      until @bottles == 0 do
        bottles = @bottles > 1 ? "bottles" : "bottle"
        puts "#{@bottles.humanize} #{bottles} of beer on the wall"
        puts "#{@bottles.humanize} #{bottles} of beer"
        puts "Take one down, pass one round"
        bottles = @bottles -1 == 1 ? "bottle" : "bottles"
        puts "#{(@bottles - 1).humanize}  #{bottles} of beer"
        @bottles -= 1
      end
    end
    

    注意这里使用了三元

    bottles = @bottles > 1 ? "bottles" : "bottle"
    

    和做的一样:

    if @bottles > 1
      bottles = "bottles"
    else
      bottles = "bottle"
    end
    

    这里使用-=

    @bottles -= 1
    

    和做的一样:

    @bottles = @bottles - 1
    

    【讨论】:

    • 很棒的答案。谢谢格里!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多