CodeDependency
CodeDependency

Reputation: 135

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?

Upvotes: 0

Views: 69

Answers (2)

user1934428
user1934428

Reputation: 22225

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

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

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.

Upvotes: 2

Related Questions