Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

372
Visualizações
How do I identify if a character/symbol is a number or not?

I'm doing a simple calculator using Ruby as practice. Everything is fine except how do I identify if a character/symbol I input is a number or not using if-else statement.

For example:

Enter first number: a
Error: Enter correct number
Enter first number: -
Error: Enter correct number
Enter first number: 1
Enter second number:b
Error: Enter correct number
Enter second number: 2
Choose operator (+-*/): *
The product is: 2

This is the code I input first:

print "Enter first number: "
x = gets.to_i
print "Enter second number: "
y = gets.to_i
print "Choose operator (+-*/): "
op = gets.chomp.to_s

I will use if-else statement to identify if the number input is a number or not

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

If you wish to test if the string represents an integer or float use Kernel#Integer or Kernel#Float with the optional second argument (a hash) having the value of the key :exception equal to false.

For example,

Integer('-123', exception: false)
  #=> -123
Integer("0xAa", exception: false)
  #=> 170
Integer('12.3', exception: false)
  #=> nil,
Integer('12a3', exception: false)
  #=> nil
Float('123', exception: false)
  #=> 123.0 
Float("1.2e3", exception: false)
  #=> 1200.0
Float('12a3', exception: false)
  #=> nil,
Float('1.2.3', exception: false)
  #=> nil

Note

Integer("123\n", exception: false)
  #=> 123

shows you don't have to chomp before testing if the string represents an integer (similar with Float).

Some of the examples illustrate a limitation or complication when using a regular expression to test whether a string represents an integer or float.

over 4 years ago · Santiago Trujillo Relatório

0

Create a new String method

irb(main):001:0> class String
irb(main):002:1>   def number?
irb(main):003:2>     Float(self) != nil rescue false
irb(main):004:2>   end
irb(main):005:1> end

irb(main):012:0> x = gets
1
=> 1
irb(main):013:0> x.number?
=> true

irb(main):009:0> x = gets
s
=> "s\n"
irb(main):010:0> x.number?
=> false
over 4 years ago · Santiago Trujillo Relatório

0

This typical way to do this would be to match it with a regexp:

x = gets.chomp
if x.match?(/^\d+$/)
  puts "#{x} is a number"
else
  puts "#{x} is not a number"     
end

This tests if the given string matches the pattern ^\d+$, which means "start of line, one or more digit characters, then end of line". Note that this won't match characters like "," or "." - only a string of the digits 0-9. String#match? will return a boolean indicating if the string matches the given pattern or not.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda