Test if a string is basically an integer in quotes

2019-01-01 10:30发布

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

标签: ruby
19条回答
只靠听说
2楼-- · 2019-01-01 11:24

I'm not sure if this was around when this question is asked but... For anyone that stumbles across this post, the simplest way is

var = "12"
var.is_a?(Integer) # returns false
var.is_a?(String) # returns true

var = 12
var.is_a?(Integer) # returns true
var.is_a?(String) # returns false

.is_a? will work with any object!

查看更多
登录 后发表回答