One way would be to check with a regular expression (the following example also allows for an explicit + sign at the start of the integer).
(
var isInteger = { |str|
var len = str.size;
var result = str.findRegexpAt("[+-]?[0-9][0-9]*");
if (result.isNil) {
false;
} {
len == result[1];
}
};
isInteger.("123.123").debug("test 1");
isInteger.("123").debug("test 2");
isInteger.("123a").debug("test 3");
isInteger.("whut").debug("test 4");
)
Not really any more dangerous than running your code in the interpreter in general. Why is the string random in this case?
“15”.interpret.isKindOf(Integer)
Also- there is an asInteger method on String. Not sure if that is safer or not but it is running it as a primitive so my gut says it probably is doing something safer.
I think running ‘interpret’ is generally safe UNLESS what is being interpreted includes .unixCmd and escaped strings:
""ls".unixCmd”.interpret
That shows that interpret CAN be used to interact with your system. But that also isn’t a very random string. So I guess it depends on how random your strings are.
However, each of the followings firstly returns an error message and then returns false!
"hats".interpret.isInteger // false after ERROR: Variable 'hats' not defined.
"hats".interpret.isKindOf(Integer) // false after ERROR: Variable 'hats' not defined.
I think it would be a good design to not crash the program because of such a small thing. That’s why some languages use Maybe values Just/Nothing. Just be careful that nothing inside .intepret will crash the program.