Question

I'm trying to assign positive integers to a list of items. The positive integers are user inputs. I'm using Ruby 1.9.3-p327

If a user inputs a negative number(anything <0) or 0 itself or decimals or any alphanumeric data, I've placed a condition in a while loop, requesting the user to input the number again.

My current code within a loop is :-

      input_data = gets.chomp
      while (input_data.to_i <= 0  || input_data.include?(".") || /^[-+]?[0-9]+$/.match(input_data).nil?)
        puts "input_data can't be 0 or a negative integer or in decimal format or alphanumeric. \nPlease input appropriate input_data as a +ve integer "
        input_data = gets.chomp
      end

I'm sure there would be a more optimal way to do this. I guess it might be using a combined regex check. I'm a novice to regex in Ruby. Any suggestions?

Thanks

Was it helpful?

Solution

Using regular expression:

input_data = gets.chomp
while input_data !~ /^[1-9]\d*$/
  puts "input_data can't be 0 or a negative integer or in decimal format or alphanumeric. \nPlease input appropriate input_data as a +ve "
  input_data = gets.chomp
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top