尝试转换并显示序号

时间:2016-05-21 15:13:00

标签: ruby

puts "Enter a number"
i = gets.chomp.to_i

def ordinal(n)
   last_number = n % 10
   special_case = n.to_s

   if special_case.include?("11") || special_case.include?("12") || special_case.include?("13")
      return "th"
   elseif last_number == 1
      return "st"
   elseif last_number == 2
      return "nd"
   elseif last_number == 3
      return "rd"
   else
      return "th"
   end
end

puts "That's the #{i}#{ordinal(i)} item!" 

无法弄清楚为什么每个答案都会返回"th"。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:0)

这是elsif,而不是ifif,在一种情况下,你比较一个字符串,另一个用数字。您不必转换为字符串来进行比较。

你的方法应该是

def ordinal(n)
   last_number = n % 10
   if [11,12,13].include?last_number
      return "th"
   elsif last_number == 1
      return "st"
   elsif last_number == 2
      return "nd"
   elsif last_number == 3
      return "rd"
   else
      return "th"
   end
end

如果结果是正确的,我不会知道,英语不是我的母语。

答案 1 :(得分:0)

除了将elseif替换为elsif之外,假设n = 21131。然后

special_case = n.to_s
  #=> "21131"
special_case.include?("11")
  #=> true

这不是你想要的。

考虑按如下方式编写方法:

def ordinal(n)
  return "th" if (11..13).include? n%100
  case n%10
  when 1 then "st"
  when 2 then "nd"
  when 3 then "rd"
  else        "th"
  end
end

puts "Enter a number"
n = gets.to_i

注意不需要chomp,例如,"23cats".to_i #=> 23

n = 211
That's the 211th item!

n = 282
puts "That's the #{n}#{ordinal(n)} item!" 
That's the 282nd item!

n = 24733
puts "That's the #{n}#{ordinal(n)} item!" 
That's the 24733rd item!

有问题。例如,最后一个应该是,#34;这是第1,4,3,33项!"。您可以修改方法以返回此字符串,但这超出了问题的范围。

答案 2 :(得分:0)

使用case语句可以获得相同的结果。

puts "Enter a number"
i = gets.chomp.to_i

def ordinal(n)
  last_number = n % 10
  case 
    when last_number == 1 && n != 11 then return "st"
    when last_number == 2 && n != 12 then return "nd"
    when last_number == 3 && n != 13 then return "rd"
    else return "th"
  end
end

puts "That's the #{i}#{ordinal(i)} item!"

希望这会有所帮助:)