0

I'm practicing a little with Ruby and I want to handle the age's input, for example if someone types "eleven" instead of 11, I want to show a message that, the person know he/she can't use a String.

Here's my code

saludo = "Hola ¿Como te llamas?"

puts saludo
STDOUT.flush
#STDOUT es una constante global que almacena las salidas del programa. flush vacía cualquier dato almacenado, y por lo tanto, limpiará cualquier resultado anterior.
nombre = gets
STDOUT.flush
puts "Entonces te llamas #{nombre}"

puts "¿Cuantos años tienes?"
edad = Integer(gets.chomp)
#gets.chomp elimina el /n de gets
#El .to_i pasa el String a Integer
if edad > 0
  if edad >= 18
    puts "Eres mayor de edad, puedes votar y esas cosas"
  else
    puts "Tienes que moverte con el permiso de tus padres."
  end
else
  puts "prueba"
end    

6 Answers6

2

I've always just done it this way. Adding a method to the String class to do the check with makes things a lot easier.

class String
  def is_i?
    !!Integer(self)
    rescue ArgumentError, TypeError
      false
  end
end

puts "1".is_i?
puts "asda".is_i?

Some people may not like it, because it uses exceptions, but I think it's fine.

Adam LeBlanc
  • 932
  • 7
  • 21
  • `self == self.to_i.to_s` is probably less messy. – tadman Jun 26 '17 at 19:37
  • That's true. It really depends on what's acceptable. – tadman Jun 27 '17 at 16:43
  • The method I made will (should) accept anything that is a valid Integer literal, which I think is ideal. I'm not sure if there's really another straight forward way to do this. Regular expressions are also a valid approach though (actually, probably better), but meh, good enough. – Adam LeBlanc Jun 27 '17 at 17:28
  • Normally I'd lean towards a regular expression, but how many digits are allowed? 10? 100? A billion? Ruby's bignum system will attempt to accommodate nearly anything. Try `Integer('9' * 1e6)` for example. – tadman Jun 27 '17 at 17:33
1

If you want to check the datatype of the input, you can use something like this:

input = gets.chomp
input.class == Fixnum

Since, every input in ruby is taken as a string, you can convert the input to integer using to_i like:

input = gets.to_i

Check if the input value is 0 which is the default value taken by the strings converted to integer as below:

if input == 0
puts("Please enter an integer")
sachin_hg
  • 136
  • 3
0

When you do Integer(gets.chomp) if gets.chomp is not an strictly integer string (i.e. 1, 2, -12, etc), it will raise an error

So you can do this:

input_string = gets.chomp
edad = nil
begin
  edad = Integer(input_string)
rescue 
  puts "#{input_string} is not an integer"
end
# edad will still be nil if there was a problem
Mitch VanDuyn
  • 2,838
  • 1
  • 22
  • 29
0

If you're using gets and you expect to receive a number, parsing this to integer, then you can "skip" the chomp, this way using gets.to_i, you can convert the input from the user in an integer, and you can see that everything that's not a number is converted to 0, so you can check if edad after the operation is 0 edad.zero?, and this way to show your message:

puts '¿Cuantos años tienes?'
edad = gets.to_i
if edad.zero?
  puts 'Debes ingresar un número'
end

You can initialize edad as 0, and then using until to create a loop, which asks the user to enter a number, so, when edad takes a non-zero value the code outs from the until loop, and you can pass the next step:

edad = 0
until !edad.zero?
  puts '¿Cuantos años tienes?'
  edad = gets.to_i
  if edad.zero?
    puts 'Debes ingresar un número'
  end
end
puts edad
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
0

input = gets.chomp

if input != "0" && input.to_i == 0
    puts "Invalid age format. Integer expected"
else
    age = input.to_i
end
Michael Malov
  • 1,877
  • 1
  • 14
  • 20
0

A more Ruby way

Use a case-expression which allows you to compare your input with string-ranges thus negating the need to use String#to_i:

#age.rb
loop do
  puts 'Enter age'
  case gets.chomp
  when /\D/
    puts 'Digits only, try again', '======================'
  when '0'..'17'
    puts 'too young'
    break
  when '18'..'120'
    puts 'old enough'
    break
  else
    puts 'Invalid age, try again', '======================'
  end
end

Using Kernel#loop ensures you continue asking the user for an input until they enter a valid age. Valid ages are defined in the case-expression as 0 - 120. If a valid age is entered the loop is broken with break.


Running the code

$ ruby age.rb
Enter age
eleven
#Digits only, try again
#======================
Enter age
10000
#Invalid age, try again
#======================
Enter age
5
#too young

$ ruby vote.rb
Enter age
35
#old enough
Community
  • 1
  • 1
Sagar Pandya
  • 9,323
  • 2
  • 24
  • 35