Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Patrick Shushereba
Patrick Shushereba
10,911 Points

Printing the ordinal Ruby

I'm trying to write a program that will print the ordinal of a number that you enter. Here is what I have so far:

puts "Enter a number:"
num = gets.chomp.to_i

ones_place = num % 10
tens_place = num % 100

if ones_place == 1 && tens_place == 1
    puts "#{num}th"
elsif ones_place == 1
    puts "#{num}st"
elsif ones_place == 2 && tens_place != 1
    puts "#{num}nd"
elsif ones_place == 3
    puts "#{num}rd"
else
    puts "#{num}th"
end

This works for a lot of numbers, but it is still having trouble. When I enter 212, I expect "212th" and I'm getting "212nd" Can someone help me? I know that I'm not too far off, but I'm having trouble seeing it.

3 Answers

Angela Visnesky
Angela Visnesky
20,927 Points

from your code: elsif ones_place == 2 && tens_place != 1 puts "#{num}nd"

ones_place = 212 % 10 leavess a remainder of 2 (which satisfies the first half of your elsif) tens_place = 212 % 100 leaves a remainder of 12(which satisfies the second half)

Patrick Shushereba
Patrick Shushereba
10,911 Points

Alright I've got the program working:

puts "Enter a number:"
num = gets.chomp.to_i

ones_place = num % 10
tens_place = num % 100

if tens_place >= 11 && tens_place <= 19
    puts "#{num}th"
end

if ones_place == 0
    puts "#{num}th"
elsif ones_place == 1
    puts "#{num}st"
elsif ones_place == 2
    puts "#{num}nd"
elsif ones_place == 3
    puts "#{num}rd"
else
    puts "#{num}th"
end

But the problem that I'm having now is that it's printing both the right answer, and the wrong answer I was getting before. How can I resolve that?

Angela Visnesky
Angela Visnesky
20,927 Points

Have you tried combining the two if statements into one?

if tens_place >= 11 && tens_place <= 19 puts "#{num}th" elsif ones_place == 0 puts "#{num}th".....

Patrick Shushereba
Patrick Shushereba
10,911 Points

I don't quite get what you mean. I'm going to try and rewrite the program as a method and see if that helps my understanding.

Patrick Shushereba
Patrick Shushereba
10,911 Points

I don't quite get what you mean. I'm going to try and rewrite the program as a method and see if that helps my understanding.