-3

I am trying to test if my variables are Integer, here is the code :

if (params[:int1].is_a?(Integer) && params[:int2].is_a?(Integer))
  add(params[:int1], params[:int2])
else
  puts "Need two integers"
end

If you know why it doesn't works, you have all my attention.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • 4
    Define "doesn't work" – Sergio Tulentsev Sep 06 '13 at 13:02
  • `is_a?` checks for the exact type and does not perform any coercion between string and integer types. My guess is your parameters are strings. Try checking if they're numeric using regular expressions or constructing the integers and catching argument errors. – toniedzwiedz Sep 06 '13 at 13:06
  • params[] is either a string, or nil. `params[].is_a?(Integer)` will never be true. – SwiftMango Sep 06 '13 at 13:30
  • Is this related to [How to add two parameters from the url](http://stackoverflow.com/questions/18656505/how-to-add-two-parameters-from-the-url)? – Stefan Sep 06 '13 at 13:50

2 Answers2

0
params= { int1: "1" }

puts params[:int1].class

> String

Your params hash probably contains string values instead of Integers. If you want to check if a string is a valid integer, you can try validating it against a regex like so:

if /\d+/=~ params[:int1]
  # do stuff
end
nurettin
  • 11,090
  • 5
  • 65
  • 85
0

params[] stores only strings. You need to cast them to integers.

Try something like:

params[:int1].empty? ? raise EmptyIntegerException : my_int1 = params[:int1].to_i
  • 1
    (Assuming it's Rails we're talking about; hash values can be anything in general. I'd also use `present? ` to move the non- exceptional code closer to the test.) – Dave Newton Sep 06 '13 at 13:13
  • You're right. But Probably I would go with something like `my_int1 = params[:int1].to_i if params[:int1].present?` instead the ternary. – Davi Koscianski Vidal Sep 13 '13 at 19:19