How to inhibit the use of letters and allowing just numbers

Hello,

I started using Ruby few weeks ago and I have a little problem:

How do I inhibit the user of using numbers instead of letters?

For exemple, I created a program that asks the user his age, but I want
the user answer it using only numbers, not letters (‘10’, not ‘ten’).
Which command do I use for returning the line ‘use just numbers’, for
exemple?

Please, tell me anything, even if it looks ‘hard’ :stuck_out_tongue:

Thank you

Hi Matt,

If you want to check that one variable is referring to a Numeric and not
a String, you can do:

def foo(input)
case input
when Numeric
process input
else
puts “You should’ve entered a number!”
end
end

If you want to filter an Array for only numbers, you can do something
like:

def foo(inputs)
inputs.select {|e| e.is_a? Numeric }
end

David

Matt Victorio wrote in post #983494:

Hello,

I started using Ruby few weeks ago and I have a little problem:

How do I inhibit the user of using numbers instead of letters?

For exemple, I created a program that asks the user his age, but I want
the user answer it using only numbers, not letters (‘10’, not ‘ten’).
Which command do I use for returning the line ‘use just numbers’, for
exemple?

Please, tell me anything, even if it looks ‘hard’ :stuck_out_tongue:

Please, always show your existing code, otherwise we are left guessing
what you’re doing.

My guess is that you’re doing something like this:

line = $stdin.gets
age = line.to_i

Here, ‘line’ is always going to be a string of characters - if the user
types 10 and hits Enter, you will get “1” “0” “\n”.

You have several ways to enforce integerness. Here is one:

line = $stdin.gets
age = Integer(line)

That raises an exception if line consists of other characters (trailing
spaces permitted). You could then rescue the exception. Note that it
also interpets numbers beginning with ‘0’ and ‘0x’ as octal and hex
respectively.

Probably a better solution is to match against a regular expression, so
you can define exactly what is or is not acceptable input.

puts “How old are you?”
while line = $stdin.gets
if line =~ /\A\d+\s*\z/
age = line.to_i
break
else
puts “Please enter a number!”
end
end
puts “Next year you will be #{age+1}”

Notes:
\A = only match at start of string
\d = match digit [0-9]
\d+ = match 1 or more digits
\s = match space
\s* = match 0 or more spaces
\z = only match at end of string

(There is a bug if the user terminates the session without entering any
age. I’ll leave that to you to fix!)

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs