Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Given a string object like this:

twohundred = "200"

What is the difference between doing:

Integer(twohundred)  #=> 200

and:

twohundred.to_i      #=> 200

Is there any difference? Is it recommended to use one among the other one?

question from:https://stackoverflow.com/questions/10093493/difference-between-integervalue-and-value-to-i

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
278 views
Welcome To Ask or Share your Answers For Others

1 Answer

Integer(num) will throw an ArgumentError exception if num isn't a valid integer (you can specify the base).

num.to_i will convert as much as it can.

For example:

"2hi".to_i 
#=> 2

Integer("2hi")
#=> throws ArgumentError

"hi".to_i
#=> 0

Integer("hi")
#=> throws ArgumentError

"2.0".to_i
#=> 2

Integer("2.0")
#=> throws ArgumentError

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...