Safe integer parsing in Ruby

Ruby has this functionality built in: Integer(‘1001’) # => 1001 Integer(‘1001 nights’) # ArgumentError: invalid value for Integer: “1001 nights” As noted in answer by Joseph Pecoraro, you might want to watch for strings that are valid non-decimal numbers, such as those starting with 0x for hex and 0b for binary, and potentially more tricky … Read more

Can I hint the optimizer by giving the range of an integer?

Yes, it is possible. For example, for gcc you can use __builtin_unreachable to tell the compiler about impossible conditions, like so: if (value < 0 || value > 36) __builtin_unreachable(); We can wrap the condition above in a macro: #define assume(cond) do { if (!(cond)) __builtin_unreachable(); } while (0) And use it like so: assume(x … Read more

Why do == comparisons with Integer.valueOf(String) give different results for 127 and 128?

There’s a striking difference here. valueOf is returning an Integer object, which may have its values cached between -128 and 127. This is why the first value returns true – it’s cached – and the second value returns false – 128 isn’t a cached value, so you’re getting two separate Integer instances. It is important … Read more