pharo-project / pharo

Pharo is a dynamic reflective pure object-oriented language supporting live programming inspired by Smalltalk.
http://pharo.org
Other
1.21k stars 356 forks source link

`String>>#asInteger` has not defined behavior #17277

Open jordanmontt opened 1 month ago

jordanmontt commented 1 month ago

The comment of the method says the following:

String >> #asInteger
    "Return the integer present in the receiver, or nil. In case of float, returns the integer part."
    ....

But is not clear. Does returns the integer represented by String, what happens if the String is not an integer.

As an example, let's look at this:

'Weird222String' asInteger. "222"
'Weird222String111' asInteger. "222"
'333Weird222String111' asInteger. "333"

If we see into the implementation, the method returns the first characters that can be parsed as an integer and it stops as soon as there is something else.

I propose to use the NumberParser to parse the String and raise an exception if the complete String does not correspond to an integer.

astares commented 1 month ago

Funny enough this seems to be the case since Squeak times. I tried in SqueakJS (squeak.js.org).

image

not a problem in Cuis or Squeak Mini image as there is no implementation of #toInteger for String

image