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?
s = gets.chomp; if s.match?(/\A(string|s)\z/i) ...or...if s.match(/\A(string|s)\z/i) ...orif s =~ /\A(string|s)\z/i .... You want\z, not\Z, for the end-of-string anchor.\Zto avoid the necessity tochompupfront.\Z, or perhaps never knew (no way to know which).\A...\Zbehaves more like^...$– both match before an optional line terminator. (which is rarely of interest)ifequivalent for thatcaseexpression? Matching various patterns against a single object is a prime example of usingcase.