Ruby code efficiency

Is there a way to make this code shorter and simpler?

loop do 
    if possibleSet.split(" ").map(&:to_i).any? {|e| (e<0 || e>12)}
        print "Please enter valid numbers (between 1 and 12): "
        possibleSet = gets
        errorinput = false
    else
        errorinput = true
    end
    break if errorinput
end

Upvotes: 0

Views: 55

Answers (3)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

The code below will check input for correctness:

input = loop do
  print "Please enter valid numbers (between 1 and 12): "
                          # ⇓⇓⇓ as many spaces as user wants
  input = gets.chomp.split(/\s+/).map(&:to_i) rescue []
  break input unless input.empty? || input.any? { |i| !(0..12).include? i }
end

Upvotes: 1

floum
floum

Reputation: 1159

This parses the user input in an array (not exactly the same behavior, but I hope it is cleaner and you can work from there)

set = []
until set.all? {|i| (1..11).include?(i) } && !set.empty? do
  set = gets.split(' ').map(&:to_i)
end

Upvotes: 0

Jason Adrian Bargas
Jason Adrian Bargas

Reputation: 254

Refactored a bit :)

loop do 
    print "Please enter valid numbers (between 1 and 12): "
    possibleSet = gets.chomp
    break unless possibleSet.split(" ").map(&:to_i).any? {|e| (e<0 || e>12)}
   end

Upvotes: 1

Related Questions