Home > Back-end >  Ruby- Help converting 4 digit year input into 2 digit output
Ruby- Help converting 4 digit year input into 2 digit output

Time:02-19

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?

CodePudding user response:

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: "d" % value, where % is a different operator, separating the template string and its arguments.

You should combine these things:

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

CodePudding user response:

Well, you'll have to update your code sample a little bit, try this:

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

CodePudding user response:

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
  •  Tags:  
  • ruby
  • Related