Using regex in simple if statements? - ruby

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

Related

What is wrong here in this Ruby Program?

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

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

Ruby detects variable is string, but ends the script without breaking loop [duplicate]

I need to check whether my variable is an Integer or a String.
The code below will just break the loop, without warning me for an illegal character. Can anyone help me to find the mistake?
x = 0
while x == 0
name = gets.chomp.capitalize
if name.empty?
puts "No input. Try again"
elsif name.is_a? Integer
puts "Illegal character: Integer "
else
x = 1
end
end
Because gets returns a string you need to find out if the string represents a number (and only a number).
First, translate your string to an integer with to_i. Please note that to_i returns 0 for strings that do not include numbers. In a second step check if translating this integer back into a string matches the original string
string.to_i.to_s == string
Note that this is just a simple example, it wouldn't work for example with the string 00.
Another way might be checking if the string only contains numbers. That could be done by using a regexp:
string.match(/\A\d+\z/)
You can do something like this:
loop do
puts "Enter name"
name = gets.chomp
if name.empty?
puts "No input, try again"
elsif name.scan(/\d+/).any?
puts "Illegal character: Integer"
else
raise StopIteration
end
end
case-expression
Or use a case-expression to tidy things up.
loop do
puts "Enter name"
case gets.chomp
when ''
puts "No input, try again"
when /\d/
puts "Illegal character: Integer"
else
raise StopIteration
end
end
See String#scan, Array#any? and StopIteration for further details

Check whether my variable is an Integer or String

I need to check whether my variable is an Integer or a String.
The code below will just break the loop, without warning me for an illegal character. Can anyone help me to find the mistake?
x = 0
while x == 0
name = gets.chomp.capitalize
if name.empty?
puts "No input. Try again"
elsif name.is_a? Integer
puts "Illegal character: Integer "
else
x = 1
end
end
Because gets returns a string you need to find out if the string represents a number (and only a number).
First, translate your string to an integer with to_i. Please note that to_i returns 0 for strings that do not include numbers. In a second step check if translating this integer back into a string matches the original string
string.to_i.to_s == string
Note that this is just a simple example, it wouldn't work for example with the string 00.
Another way might be checking if the string only contains numbers. That could be done by using a regexp:
string.match(/\A\d+\z/)
You can do something like this:
loop do
puts "Enter name"
name = gets.chomp
if name.empty?
puts "No input, try again"
elsif name.scan(/\d+/).any?
puts "Illegal character: Integer"
else
raise StopIteration
end
end
case-expression
Or use a case-expression to tidy things up.
loop do
puts "Enter name"
case gets.chomp
when ''
puts "No input, try again"
when /\d/
puts "Illegal character: Integer"
else
raise StopIteration
end
end
See String#scan, Array#any? and StopIteration for further details

Accept only numeric input

I want to force user to enter only numeric value from console. Below is my piece of code that is supposed to do that.
puts "Enter numeric value: "
result = gets.chomp
if result.to_i.is_a? Numeric
puts "Valid input"
else
puts "Invalid input."
end
It prints Valid input even if I enter a string value. And the reason is that every string has some equivalent numeric value in Ruby. Can someone help me fix the condition properly so that when user enters a non-numeric value, the script prompts Invalid input.?
to_i will convert any string to an integer, even if it shouldn't:
"asdf".to_i
which returns 0.
What you want to do is:
puts "Enter numeric value: "
result = gets.chomp
begin
result = Integer(result)
puts "Valid input"
rescue ArgumentError, TypeError
puts "Invalid input."
# handle error, maybe call `exit`?
end
Integer(some_nonnumeric_string) throws an exception if the string cannot be converted to an integer, whereas String#to_i gives 0 in those cases, which is why result.to_i.is_a? Numeric is always true.
Try regular expressions, like this:
puts "Enter numeric value: "
result = gets
if result =~ /^-?[0-9]+$/
puts "Valid input"
else
puts "Invalid input."
end
The example above allows only digits [0..9].
If you want to read not only integers, you can allow a dot as well: ^-?[0-9]+$/. Read more about regexp in Ruby: http://ruby-doc.org/core-2.2.0/Regexp.html
If you mean integer by "numeral", then:
puts "Enter numeric value: "
result = gets.chomp
case result
when /\D/, ""
puts "Invalid input"
else
puts "Valid input."
end
It also takes care of empty strings, which would be turned into 0 by to_i, which you probably do not want.

Resources