Home > Back-end >  What is wrong here in this Ruby Program?
What is wrong here in this Ruby Program?

Time:09-11

I want in brief to run a program to check if the user input is empty to let him reinsert the needed data and in case there is "s" in the string to be substituted with another letter

print "Please enter a string: "
user_input = gets.chomp.downcase!

if user_input.empty?
  print "Please enter a vaild string... "
  user_input = gets.chomp.downcase!

elsif
  user_input.include? "s"
  user_input.gsub!(/s/, "th")
else
  puts "There are no 's's in your string. #{user_input}"
end

puts "Your new thtring is #{user_input}."

CodePudding user response:

The problem is with this line

user_input = gets.chomp.downcase!

according to the docs

Downcases the contents of str, returning nil if no changes were made.

So if the user inputs a string with only lowercase letters, nil is returned.

Your function works if a user enters FOO, then it works fine.

You're better off using downcase instead of downcase!. downcase always return the string itself.

CodePudding user response:

As I understand you need get valid user input (with s)

Now you are only using if and this does not guarantee that user input will be valid

You can refactor to something like this

puts "Please enter a string with s:"

thtring = ""

loop do
  user_input = gets.chomp

  next puts "Please enter some string..." if user_input.empty?

  thtring = user_input.downcase

  next puts "There are no 's's in your string" unless thtring.include?("s")

  break thtring.gsub!(/s/, "th")
end

puts "Your new thtring is #{thtring}."

CodePudding user response:


print "Please enter a string: "
user_input = gets.chomp.downcase

if user_input.empty?
  print "Please enter a vaild string... "
  user_input = gets.chomp.downcase!

elsif user_input.include? "s"
  user_input.gsub!(/s/, "th")
else
  puts "There are no 's's in your string. #{user_input}"
end

puts "Your new thtring is #{user_input}."
  •  Tags:  
  • ruby
  • Related