0

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?

5
  • 1
    s = gets.chomp; if s.match?(/\A(string|s)\z/i) ... or ...if s.match(/\A(string|s)\z/i) ... or if s =~ /\A(string|s)\z/i .... You want \z, not \Z, for the end-of-string anchor. Commented Feb 12, 2020 at 5:21
  • 1
    @CarySwoveland how come? They want indeed \Z to avoid the necessity to chomp upfront. Commented Feb 12, 2020 at 5:39
  • @AlekseiMatiushkin, I forgot about \Z, or perhaps never knew (no way to know which). Commented Feb 12, 2020 at 5:42
  • \A...\Z behaves more like ^...$ – both match before an optional line terminator. (which is rarely of interest) Commented Feb 12, 2020 at 7:54
  • BTW, why are you asking for an if equivalent for that case expression? Matching various patterns against a single object is a prime example of using case. Commented Feb 12, 2020 at 8:07

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

"\Z - Matches end of string. If string ends with a newline, it matches just before newline" - Ruby Doc
1

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

2 Comments

Why would anyone sane want to turn a clean case into elsif spaghetti?
I don't know. I didn't say that it is a good idea. Just the OP wanted to know - maybe out of theoretical interest?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.