(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.