使用数组将给定数字转换为单词

时间:2016-03-24 15:15:07

标签: ruby

我正在尝试为经典的啤酒瓶输出创建方法。

给定一个数字@beers,我想将其转换为数字的单词版本。我想将数字拆分成一个数组,然后将数字列表与单词进行比较:

class BeerSong

  attr_accessor :beers

  def initialize(beers)

    if beers > 99
      beers = 99
    elsif beers < 1
      beers = "Zero"
    end
    @beers = beers
  end


  def worded
    num_name = {      
      90 => "Ninety", 80 => "Eighty", 70 => "Seventy",60 => "Sixty",
      50 => "Fifty",40 => "Forty",30 => "Thirty",20 => "Twenty",
      19 => "Nineteen", 18 => "Eighteen",  17 => "Seventeen", 16 => "Sixteen",
      15 => "Fifteen",14 => "Fourteen", 13 =>"Thirteen",  12 => "Twelve",
      11 => "Eleven", 10 => "Ten",  9 => "Nine",8 => "Eight", 7 => "Seven",
      6 => "Six",5 => "Five",4 => "Four",3 => "Three",2 => "Two",1 => "One"
    }


    worded = ""

    beers = @beers

    split_beers = beers.to_s.split

    num_name.each do |number, name|
      split_number = number.to_s.split
      if beers == number
        worded << name
      else
        number > 19 && split_number[0].to_i == split_beers[0].to_i
        worded << name
        worded << "-"
      end
    end

    num_name.each do |number, name|
      if number < 10 && split_beers[1].to_i == number
        worded << name
      end
    end

    worded

  end

  def print_song

    while @beers.to_i > 2

      puts "#{worded} bottles of beer on the wall,"
      puts "#{worded} bottles of beer,"
      puts "Take one down, pass it around,"
      @beers -= 1
      puts "#{worded} bottles of beer on the wall.\n\n"
    end

    if @beers.to_i == 2
      puts "#{worded} bottles of beer on the wall,"
      puts "#{worded} bottles of beer,"
      puts "Take one down, pass it around,"
      @beers -= 1
      puts "#{worded} bottle of beer on the wall.\n\n"
    end

    if @beers.to_i == 1
      puts "#{worded} bottle of beer on the wall,"
      puts "#{worded} bottle of beer,"
      puts "Take one down, pass it around,"
      puts "Zero bottles of beer on the wall.\n\n"
    end

    if @beers.to_i == 0
      print ""
    end

  end

end

我正在尝试比较第一个数字以获得数字,然后比较用连字符分隔的单位的第二个数字。

1 个答案:

答案 0 :(得分:0)

你的台词:

NULL

假设一个数组结果不是这种情况,因为您没有提供要拆分的模式 所以使用默认值。请参阅:http://ruby-doc.org/core-2.0.0/String.html#method-i-split

split_beers = beers.to_s.split
split_number = number.to_s.split

最后一个是你想要的。