'Ruby- Help converting 4 digit year input into 2 digit output

So far I have.

puts "Enter year:"
year = gets.chomp.to_i
res = year %2 100
puts "Welcome to '#{year}"

Where am I going wrong?



Solution 1:[1]

I think you are mixing up 2 things:

  1. Getting the "last part" (modulo 100) of the year: year % 100, where % is the modulo operator.

  2. And printing out a value with 2 digits using leading zeros: "%02d" % value, where % is a different operator, separating the template string and its arguments.

You should combine these things:

year = 2002
res = "%02d" % (year % 100)
puts res
# 02

Solution 2:[2]

Others have already pointed out most of the issues with your specific code, so I won't do that. I did however want to suggest that you shouldn't even need to convert to integer or use modulo. You should be able to simply use the string and take the last 2 characters:

year = gets.chomp
puts "Welcome to '#{year[-2..-1]}"
#=>  Welcome to '22

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 juzraai
Solution 2 Michael B