我的代码适用于除 11、12 和 13 或以最后两位数字结尾的数字之外的所有内容。
def ordinal()
n = gets.chomp.to_i
suffix = n % 10
if suffix == 1
return "That's the #{n}st item!"
elsif suffix == 2
return "That's the #{n}nd item!"
elsif suffix == 3
return "That's the #{n}rd item!"
else
return "That's the #{n}th item!"
end
end
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激!谢谢。
这是一个特殊情况。在检查 1 位数后缀之前先检查 2 位数后缀。像这样的东西
def ordinal(n)
ending = case n % 100
when 11, 12, 13 then 'th'
else
case n % 10
when 1 then 'st'
when 2 then 'nd'
when 3 then 'rd'
else 'th'
end
end
"This is #{n}#{ending} item"
end
ordinal(1) # => "This is 1st item"
ordinal(10) # => "This is 10th item"
ordinal(12) # => "This is 12th item"
ordinal(15) # => "This is 15th item"
ordinal(112) # => "This is 112th item"
ordinal(123) # => "This is 123rd item"
Run Code Online (Sandbox Code Playgroud)