What is wrong here in this Ruby Program? - ruby

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}."

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.

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}."

Related

Using regex in simple if statements?

Instead of doing:
puts "what type of input?"
input = gets.chomp
if %W[Int INT i I Ints ints].include?(input)
puts "enter int"
i = gets.to_i
I want to use regex to interpret string user input. For example,
puts "are you entering in a string, an int or a float?"
case gets
when /\A(string|s)\z/i
puts "enter in a string"
gets.chomp
when /\A(int|i)\z/i
puts "enter an int"
gets.to_i
when /\A(float|f)\z/i
puts "enter a float"
gets.to_f
end
What is the syntax in order to get the same result but using if statements instead of case statement?
gets returns a string with a trailing carriage return. What you need is to match the ending against \Z, not \z.
puts "are you entering in a string, an int or a float?"
case gets
when /\As(tring)?\Z/i
puts "enter in a string"
gets.chomp
when /\Ai(nt)?\Z/i
puts "enter an int"
gets.to_i
when /\Af(loat)?\z/i
puts "enter a float"
gets.to_f
else puts "Didn’t work"
end
I also slightly updated regexps to clearly show the intent.
If you want to turn your case into an if, you have to store the expression intended for the gets into a variable:
response=gets.chomp
if /..../ =~ response
...
elsif /.../ =~ response
....
....
else
...
end

How do I request user input until user enters valid input in ruby?

This is a problem where they have asked me to add an additional if statement to re-prompt the user for input if they don't enter anything.
I have tried to use the while loop, but still can't solve the problem
print "please enter a sentence with a letter s"
while user_input = gets.chomp.downcase!
case user_input
when user_input.include? "s"
user_input.gsub(/s/,"th")
print "Daffy Duck says #{user_input}"
break
else
print "please enter a sentence with a letter s"
end
I expect "please enter a sentence with a letter s" to loop until the user enters the letter "s"
My understanding is that the user enters sentences until one contains an "s" or an "S", at which time a certain action is taken and the program terminates.
Let's go through what you have.
print "Please enter a sentence with a letter s"
I think you want puts, which adds a newline character, rather than print, which does not.
while user_input = gets.chomp.downcase!
Suppose the user enters "Cat" (even though it's not a sentence), then presses the Enter key, then
str0 = gets
#=> "Cat\n"
str1 = str0.chomp
#=> "Cat"
user_input = str1.downcase!
#=> "cat"
str1
#=> "cat"
user_input
#=> "cat"
so we have
while "cat"
As "cat" is neither false nor nil (the only logical false objects), this is the same as
while true
so execution moves to the first statement within the while loop. Suppose instead the user entered "cat" and pressed the Enter key. Then
str0 = gets
#=> "cat\n"
str1 = str0.chomp
#=> "cat"
user_input = str1.downcase!
#=> nil
str1
#=> "cat"
user_input
#=> nil
so the program would not enter the while loop! How, you ask, can "cat".downcase return nil? Look at the doc for String#downcase!. It shows that nil is returned if there were no characters to downcase. Ruby has many methods that do the same: if the receiver is not altered nil is returned. (Don't get sidetracked with "why" at this point of your education.) For the present you are advised to avoid using bang methods (ending with an "!").
Similarly, if the user didn't enter anything and pressed enter,
str1 = "\n".chomp
#=> "" (an empty string)
user_input = str1.downcase
#=> nil
"".downcase! returns nil for the same reason that "cat".downcase! does.
I think what you what here is the following.
user_input = gets.chomp
while !user_input.match?(/s/i)
/s/i is a regular expression used to determine if the string contains an "s" or an "S". i in /i is a case-indifference modifier. (One could instead write while user_input !~ /s/i.)
The first statement within the while loop is
case user_input
When case has an argument (here user_input) the when statements contain arguments that are possible values of the case argument, for example
case user_input
when "call me silly!"
puts "You are silly"
when...
You are not doing that here, so you want case on a line by itself:
case
when user_input == ...
...
end
Here, however, there is no need for a case statement or "if/elsif/else/end" construct within the loop because we have already determined that user_input does not contain an "s". All we need in the loop is this:
while !user_input.match?(/s/i)
puts "Please enter a sentence with a letter s"
user_input = gets.chomp
end
After the loop is terminated user_input is a string that contains an "s". We therefore need only perform the following.
puts "Daffy Duck says #{user_input}"
#=> "Quack, quack, quackity-quack, sir"
Note that your statement
user_input.gsub(/s/, "s")
substitutes each "s" with an "s". :-) Nor is there a need for the break keyword.
Putting all this together, you could write:
puts "Please enter a sentence with a letter s"
user_input = gets.chomp
while !user_input.match?(/s/i)
puts "Please enter a sentence with a letter s"
user_input = gets.chomp
end
puts "Daffy Duck says #{user_input}"
You thought I was finished. Not so fast!
Firstly, many Ruby coders try to avoid negations such as while !user_input.match?(/s/i) (though it is purely a matter of taste). You could instead write that line
until user_input.match?(/s/i)
A more significant problem is the replication of code. You can improve upon that by using Kernel#loop and the keyword break instead of while or until.
loop do
puts "Please enter a sentence with a letter s"
user_input = gets.chomp
if user_input.match?(/s/i)
puts "Daffy Duck says #{user_input}"
break
end
end
If, however, we wrote
loop do
puts "Please enter a sentence with a letter s"
user_input = gets.chomp
break if user_input.match?(/s/i)
end
puts "Daffy Duck says #{user_input}"
The last line would raise the exception
NameError (undefined local variable or method `user_input' for main:Object)
because the variable user_input is only defined within the loop.
I generally use loop and break in preference to while or until.
Is your problem a program not working?
What do you want to do the following?
please enter a sentence with a letter s: a
please enter a sentence with a letter s: s
Daffy Duck says: s
in this case,
print "please enter a sentence with a letter s: "
while user_input = gets
user_input.chomp.downcase!
if user_input.include? "s"
user_input.gsub(/s/,"s")
print "Daffy Duck says: #{user_input}"
return
else
print "please enter a sentence with a letter s: "
end
end
The i after /s/ is case-insensitive search.
If the string has an s and we remove it, the
original will not match
puts "please enter a sentence with a letter s"
while user_input = gets
user_input = user_input.chomp
if user_input != user_input.gsub(/s/i,"")
puts "Daffy Duck says: #{user_input}"
break
else
puts "please enter a sentence with a letter s"
end
end
The match location will be a zero-based integer index if found
or nil if no match
puts "please enter another sentence with a letter s"
while user_input = gets
user_input = user_input.chomp
match_location = user_input =~ /s/i
if match_location.nil?
puts "please enter a sentence with a letter s"
else
puts "Daffy Duck says: #{user_input}"
break
end
end

How to re-prompt and re-use a user's input

I was trying to re-prompt a user's input and reuse it. Here's the code sample:
print "Please put your string here!"
user_input = gets.chomp
user_input.downcase!
if user_input.include? "s"
user_input.gsub!(/s/,"th")
elsif user_input.include? ""
user_input = gets.chomp
puts "You didn't enter anything!Please type in something."
user_input = gets.chomp
else
print "no \"S\" in the string"
end
puts "transformed string: #{user_input}!"
My elsif will let the user know that their input was not acceptable, but was not effective in re-using their input to start from the beginning. How am I supposed to do it? Should I use a while or for loop?
Hope this solves your problem :)
while true
print 'Please put your string here!'
user_input = gets.strip.downcase
case user_input
when ''
next
when /s/
user_input.gsub!(/s/, "th")
puts "transformed string: #{user_input}!"
break
else
puts "no \"S\" in the string"
break
end
end
You can have a loop at the beginning to continuously ask for input until it's valid.
while user_input.include? "" #not sure what this condition is meant to be, but I took it from your if block
user_input = gets.chomp
user_input.downcase!
end
This will continuously ask for input until user_input.include? "" returns false. This way, you don't have to validate input later.
However, I'm not sure what you are trying to do here. If you want to re-prompt when the input is empty, you can just use the condition user_input == "".
EDIT: Here's the doc for String.include?. I tried running .include? "" and I get true for both empty and non-empty input. This means that this will always evaluate to true.
user_input = nil
loop do
print "Please put your string here!"
user_input = gets.chomp
break if user_input.length>0
end
user_input.downcase!
if user_input.include? "s"
user_input.gsub!(/s/,"th")
else
puts "no \"S\" in the string"
end
puts "transformed string: #{user_input}!"

How to display modified string?

I am creating a Daffy Duck speech converter (Very simple. Straight from CodeCademy) and I am having an issue with displaying the modified entry from the user.
Code:
puts "What would you like to convert to Daffy Duck language?"
user_input = gets.chomp
user_input.downcase!
if user_input.include? "s"
user_input.gsub!(/s/, "th")
print #{user_input}
else puts "I couldn't find any 's' in your entry. Please try again."
end
It will change any 's' in your entry to a 'th', therefore, making it sound like a Daffy Duck once read aloud. When I enter it into the interpreter, it will not display the modified string. It will just display the original entry by the user.
EDIT:
Thanks to the users below, the code is fixed, and I added a notice to the user with converted text. Thanks guys!
A # outside a string starts a comment, so #{user_input} is ignored, i.e.
print #{user_input}
is equivalent to
print
You might wonder why a single print outputs the original input. This is because without arguments print will print $_. That's a global variable which is set by gets:
user_input = gets.chomp # assume we enter "foo"
user_input #=> "foo"
$_ #=> "foo\n"
Everything works as expected if you pass a string literal:
print "#{user_input}"
or simply
print user_input
Note that gsub! returns nil if no substitutions were performed, so you can actually use it in your if statement:
if user_input.gsub!(/s/, "th")
print user_input
else
puts "I couldn't find any 's' in your entry. Please try again."
end
You just need to add double quotes around the string interpolation. Otherwise your code was just returning the input.
puts "What would you like to convert to Daffy Duck language?"
user_input = gets.chomp
user_input.downcase!
if user_input.include? "s"
user_input.gsub!(/s/, "th")
print "#{user_input}"
else
puts "I couldn't find any 's' in your entry. Please try again."
end
You don't even need interpolation, actually. print user_input works. Notice how StackOverflow was even syntax highlighting your code as a comment. :)

Ruby downcase method not working as expected

I am writing a small bit of code in Ruby that is supposed to redact a word that is specified by the user, regardless if the word that is being passed is all uppercase, lowercase or a combination of the two. The way that I tried to get around this was by just using the downcase! method on the strings being passed by the user. However, it would seem that it does not work correctly. For example, if the first string that is passed and stored in the variable "text" is in all uppercase and the second string that is passed and stored in the variable "redact" is all downcase, the program will fail to redact the word and will just print out everything in downcase.
Here is the code below:
puts "Enter what you want to search through"
text = gets.chomp.downcase!
puts "Enter word to be redacted"
redact = gets.chomp.downcase!
words = text.split(" ")
words.each do |word|
if word == redact
print "REDACTED "
else
print word + " "
end
end
The problem is that you use downcase! which will return nil if no change is made. The string itself is modified but the returned value is nil, which you save after in your text variable.
See the documentation about downcase and downcase! to understand the difference.
puts "Enter what you want to search through"
text = gets.chomp.downcase
puts "Enter word to be redacted"
redact = gets.chomp.downcase
words = text.split(" ")
words.each do |word|
if word == redact
print "REDACTED "
else
print word + " "
end
end
try it without the exclamation marks.

Resources