2 ms·
I agree it isn't entirely obvious at first glance why slice behaves the way it does, there is a pattern. If the first number in the range is a valid index into
by sqeaky 2y ago
I agree it isn't entirely obvious at first glance why slice behaves the way it does, there is a pattern. If the first number in the range is a valid index into the string then you'll get something back, and if it isn't you can't get anything back so you have to get back a nil.
Coming from a C++ background my time in Ruby was weird and enlightening, it was less specified than C++, but pretty much everything is. I don't think it was underspecified, but a lot of the behavior was meant to be intuited and follows some kind of underlying pattern. If you miss the pattern you miss a lot of the functionality of that part of the language.
I agree that failing early and often is generally preferable. I don't see that Ruby doesn't do that, it just has more definitions for generic behaviors. Consider the amount of things in the range from the original post that produce type errors. Last time I checked both the C++ language and the C++ standard Library both had about twice as many pages in The Standard than all of Ruby in its standard Library have, yet there is still undefined and implementation to find behavior. So there are places where we get weird an unexpected Behavior that can result in bad State being passed around even in very formally specified places.
- wavemode 2y ago> If the first number in the range is a valid index into the string then you'll get something back, and if it isn't you can't get anything back so you have to get back a nil But, 3 is not a valid index into a string of 3 characters. By your criteria, "abc"[3] correctly returns nil. Whereas "abc"[3,1] returns "" The language designers really just did not think this through.