`<=': comparison of Integer with String failed (Argumenterror)

Asked

Viewed 50 times

0

I want to know the age, then I made the following code:


nascimento = "12/34/5678"
dia =  nascimento[0,2]
mes =  nascimento[3,2]
ano =  nascimento[6,4]
dia.to_i
mes.to_i
ano.to_i
age = 2020 - 2000 #ano atual menos ano do usuario
if 8 <= mes && 14<dia #verifico se o mes atual é menor do mes do aniversariante e se o dia atual é menor que o mes dito pelo usuario
    age-=1 
end


puts dia
puts mes
puts ano
puts "Age #{age}"

But I get the following mistake:

<=': comparison of Integer with String failed (Argumenterror)

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site.

1 answer

1

You have not saved the converted value to integer anywhere, then the conversion is done and the result is thrown away and the variable remains one string.

The ideal is to do the conversion at once, so it already creates the variable of the type it should be. This is one of the problems that dynamic typing languages brings.

I’m not going to make a test if the conversion worked because the data is explicit and does not come from outside, if it came you need to check if it worked. On the other hand, as the data is known it does not make much sense a complex code. I understand it’s just an exercise, but either do something real or do something simple, this way gives the impression that this is the right to do.

There are other problems in the calculation that I decided not to touch.

nascimento = "12/34/5678"
dia =  nascimento[0,2].to_i
mes =  nascimento[3,2].to_i
ano =  nascimento[6,4].to_i
age = 2020 - 2000
if 8 <= mes && 14 < dia
    age -= 1 
end
puts dia
puts mes
puts ano
puts "Age #{age}"

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.