On Wed, Nov 30, 2016 at 7:36 AM, Nathan Guilty <ruby / e-solutions.re> wrote:
> Hi,
>
> Is it possible to do this simpler ?
>
> --8<--
>
> # Check if your input is a number, quit if input is equal to 'quit'
> class Testing_input_number
>   def initialize
>     answer = nil
>     while a_number?(answer) != true
>       answer = ask
>       puts 'Please, a number.' unless a_number?(answer)
>     end
>     puts "OK, this is a number."
>   end
>
>   def ask
>     print "Try?\s"
>     number = gets.chomp
>     bybye if number == 'quit'
>     number
>   end
>
>   def a_number?(number)
>     number.to_s == number.to_i.to_s
>   end
>
>   def bybye
>     puts "Goodbye."
>     exit
>   end
> end
>
> player = Testing_input_number.new

If this is some kind of REPL you could do

def work_with_number(i)
  printf "Got: %10d\n", i
end

loop do
  print "Your input, please: "
  input = gets.chomp

  case input
  when /\A\s*(\d+)\s*\z/
    work_with_number(Integer($1))
  when /\A\s*quit\s*\z/
    puts "Terminating."
    break
  else
    $stderr.puts "ERROR: invalid input: #{input}"
  end
end

If you only want to read an integer, you could do

def input_number
  begin
    print "Input a number, please: "
    Integer(gets.chomp)
  rescue ArgumentError => e
    puts e # "Not a number"
    retry
  end
end

i = input_number

and the result of this function is the integer value

Kind regards

robert


-- 
[guy, jim, charlie].each {|him| remember.him do |as, often| as.you_can
- without end}
http://blog.rubybestpractices.com/

Unsubscribe: <mailto:ruby-talk-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>