From: sto.mar@... Date: 2013-07-31T05:35:58+09:00 Subject: Re: How to check an input IS an integer ? Am 30.07.2013 20:51, schrieb Captain Ishido: > Le 30/07/2013 12:55, sto.mar@web.de a 辿crit : >> Am 30.07.2013 12:03, schrieb Captain Ishido: >>> Hi everyone ! >>> I have a little problem since a few days. I would like to check that my >>> user (I am writing a small program) had type an integer while I asked him. >> >> There are several possibilities, the one I like best in this case >> is using a Regex (Note that user input is always a String): >> >> 2.0.0p247 :005 > answer = '123' >> => "123" >> 2.0.0p247 :006 > /\A[0-9]+\z/ === answer >> => true >> 2.0.0p247 :007 > answer = '123abc' >> => "123abc" >> 2.0.0p247 :008 > /\A[0-9]+\z/ === answer >> => false >> >> Other possibilities can easily be found by searching the archives, >> e.g. using Integer(), (which involves rescuing exceptions, which I >> do not like for this use case too much). >> >> Regards, >> Marcus >> >> > I've found a 'solution'. I don't like it but *cough* it works. > If you're a REAL programmer, don't read. > ----------------------------------------------- > # Let's do DIRTY things > # (Don't try do to this at home, kids !) > answer="" > answer=answer.to_i > while answer == 0 do > puts "Please type an integer : " > answer = readline.chomp > answer=answer.to_i > end Depending on the use case, `0' might be a valid answer... Something like this should work: answer = nil until /\A[0-9]+\z/ === answer print 'Enter an integer: ' answer = gets.chomp end number = answer.to_i puts "Your answer: #{number}" Regards, Marcus -- GitHub: https://github.com/stomar/ PGP: 0x6B3A101A