-2

So as I ask for in the title. How do I make a loop that breaks when the user has entered some values that contain only number, and if not it will say try again.

prompt = "> "
    puts "What is the salary for the accountant: "
    print prompt 
    while accountant = gets.chomp

      if accountant == (0..9)
        puts "Nice"

        break

      else 
        "try again"
        print prompt
      end 
    end 

      end 
  • Right now you are comparing a `String` ( `accountant = gets.chomp`) to a `Range` (`(0..9)`) which will never be equivalent. What you want is to see if a number is in the range so `(0..9).cover?(accountant.to_i)` should work for you – engineersmnky Nov 22 '17 at 14:42
  • 2
    `if accountant =~ /\A\d+\z/` – Aleksei Matiushkin Nov 22 '17 at 14:45
  • Also note that invalid answers will convert to zero - e.g. `"a".to_i == 0`. So a regex may be a better approach, as suggested above. – Tom Lord Nov 22 '17 at 14:46
  • I found it out, used this if accountant =~ /^-?[0-9]+$/ – Anders Klingsholm Nov 22 '17 at 14:47
  • 1
    So a negative salary is permitted. Poor employees :D Anyway, I'd move to `/\A-?[0-9]+\z/` or something with a newline and something that is not a number would match. what @mudasobwa did suggest is good – Ursus Nov 22 '17 at 14:48
  • You could use this `if (0..9).map(&:to_s).include?(accountant)` – Oli Crt Nov 22 '17 at 15:36

2 Answers2

1

A simple solution with no regex would be:

accountant.chars.all?{|n| ("0".."9") === n}

You may want to read about the "===" operator in Ruby if you don't how it works yet as it may be confusing if you come from PHP or Javascript.
What does the "===" operator do in Ruby?

Oli Crt
  • 1,123
  • 1
  • 11
  • 13
0

Your problem is in this line:

if accountant == (0..9)

This is checking whether the value is equal to a range - which is not what you wanted.

Since the input from gets.chomp will always be a string, you need to check whether it only contains the characters: "0", "1", "2", ... and "9".

One way to do this is with a regular expression:

if accountant =~ /\A\d+\z/
  • \A means "start of string"
  • \z means "end of string"
  • \d+ means "one or more digit" (0-9)

Note that the solution you suggested in the comments, /^-?[0-9]+$/, is flawed since:

  • ^ means "start of line" (so it would be possible to insert arbitrary other characters before a newline)
  • $ means "end of line" (so it would be possible to insert arbitrary other characters after a newline)
  • -? also allows an optional hyphen character. Which is presumably not what you want in this context, since the input is a salary - which surely cannot be negative!
Tom Lord
  • 27,404
  • 4
  • 50
  • 77