将Fixnum转换为Ruby中的单词

时间:2014-05-06 07:04:31

标签: ruby

出于某种原因,我的代码什么也没显示。它应显示'one'。关于它为什么不是的任何想法?

## write function that takes a number
## check length of number
## if length is one
## conditional statements for each ones digit

def nums_to_words(num)
    length = num.to_s.length
    string = length.to_s

    if string.length < 2
        elsif string[0] == '1'
            puts 'one'
        elsif string[0] == '2'
            puts 'two'
        elsif string[0] == '3'
            puts 'three'
        elsif string[0] == '4'
            puts 'four'
        elsif string[0] == '5'
            puts 'five'
        elsif string[0] == '6'
            puts 'six'
        elsif string[0] == '7'
            puts 'seven'
        elsif string[0] == '8'
            puts 'eight'
        elsif string[0] == '9'
            puts 'nine'
    end
end


nums_to_words(1)

2 个答案:

答案 0 :(得分:1)

这个怎么样:

NUMBERS = [ 'zero', 'one' 'two', 'three', 'four', 'five', 'six', 'seven', 'eigth', 'nine' ]
def nums_to_words(num)
  str = num.to_s
  if str.size == 1
    puts NUMBERS[str.to_i]
  end
end

答案 1 :(得分:0)

这是正确答案:

def nums_to_words(num)
    length = num.to_s.length
    num = num.to_s

    if num.length < 2
        if num[0] == '1'
            puts 'one'
        elsif num[0] == '2'
            puts 'two'
        elsif num[0] == '3'
            puts 'three'
        elsif num[0] == '4'
            puts 'four'
        elsif num[0] == '5'
            puts 'five'
        elsif num[0] == '6'
            puts 'six'
        elsif num[0] == '7'
            puts 'seven'
        elsif num[0] == '8'
            puts 'eight'
        elsif num[0] == '9'
            puts 'nine'
        end
    end
end


nums_to_words(3)