I need a function, is_an_integer, where
"12".is_an_integer? returns true
"blah".is_an_integer? returns false
how can i do this in ruby? i would write a regex but im assuming there is a helper for this that i am not aware of
I need a function, is_an_integer, where
"12".is_an_integer? returns true
"blah".is_an_integer? returns false
how can i do this in ruby? i would write a regex but im assuming there is a helper for this that i am not aware of
You can use Integer(str) and see if it raises:
def is_num?(str)
Integer(str)
rescue ArgumentError
false
else
true
end
Addendum: It should be pointed out that while this does return true for "01", it does not for "09", simply because 09 would not be a valid integer literal.
Well, here's the easy way:
class String
def is_integer?
self.to_i.to_s == self
end
end
>> "12".is_integer?
=> true
>> "blah".is_integer?
=> false
EDIT: I don't agree with the solutions that provoke an exception to convert the string - exceptions are not control flow, and you might as well do it the right way. That said, my solution above doesn't deal with non-base-10 integers. So here's the way to do with without resorting to exceptions:
class String
def integer?
[ # In descending order of likeliness:
/^[-+]?[1-9]([0-9]*)?$/, # decimal
/^0[0-7]+$/, # octal
/^0x[0-9A-Fa-f]+$/, # hexadecimal
/^0b[01]+$/ # binary
].each do |match_pattern|
return true if self =~ match_pattern
end
return false
end
end
class String
def integer?
Integer(self)
return true
rescue ArgumentError
return false
end
end
is_
. I find that silly on questionmark methods, I like "04".integer?
a lot better than "foo".is_integer?
."01"
and such.You can use regular expressions:
def isint(str)
return str =~ /^[-+]?[0-9]+$/
end
heh ... first time coding in ruby ... huray!
[edit] here is the function with janm's suggestions .. thanks man!
class String
def is_i?
!!(self =~ /^[-+]?[0-9]+$/)
end
end
[/edit]
You can do a one liner:
str = ...
int = Integer(str) rescue nil
if int
int.times {|i| p i}
end
or even
int = Integer(str) rescue false
Depending on what you are trying to do you can also directly use a begin end block with rescue clause:
begin
str = ...
i = Integer(str)
i.times do |j|
puts j
end
rescue ArgumentError
puts "Not an int, doing something else"
end