Question

I'm trying to get integer from string '(3)'. However method to_i returns 0. It seems that brackets with quotes cause the problem, but I don't understand the reason.

'3'.to_i => 3
(3).to_i => 3
'(3)'.to_i => 0

Why does it happen and how to solve it? Thank you!

Was it helpful?

Solution

String#to_i ignores trailing (non numeric) characters:

"3foo".to_i         #=> 3
"3)".to_i           #=> 3

Leading (non numeric) characters don't work and return 0:

"foo3".to_i         #=> 0
"(3".to_i           #=> 0

You can extract the integer part using a regular expression:

"(3)"[/-?\d+/]      #=> "3"

And convert that to an integer:

"(3)"[/-?\d+/].to_i #=> 3

OTHER TIPS

(3) is an expression, not a string; it evaluates to a number 3.

'3' is a string literal, it doesn't evaluate to any number, but can be cast to it with to_i. The rules are quite simple:

Returns the result of interpreting leading characters in str as an integer base base (between 2 and 36). Extraneous characters past the end of a valid number are ignored. If there is not a valid number at the start of str, 0 is returned. This method never raises an exception when base is valid.

'(3)' is another string literal, again it doesn't evaluate to any number by itself. The problem is that you won't be able to make the parser 'understand' somehow that ( in the beginning of this particular string should be treated as a separator - and essentially ignored. That's not how it works.

One possible solution is to replace the ( symbol at the beginning of the string with sub (as trailing non-digit symbols are ignored by to_i):

'(3)'.sub(/^\(/, '').to_i => 3

But I really wonder why do you get the parenthesis in the first place here.

(3) is a Ruby expression, and '(3)'.to_i doesn't work for the same reason that 'Math.sqrt(9)'.to_i doesn't work.

If it helps, you can use a regexp to pick out the part of the string that is a number, and convert that

puts '(3)'[/\d+/].to_i

output

3
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top