Beware of Ruby’s string split function

Observe this behavior:





And the description in the documentation:

“If the limit parameter is omitted, trailing null fields are suppressed. If limit is a positive number, at most that number of fields will be returned (if limit is 1, the entire string is returned as the only entry in an array). If negative, there is no limit to the number of fields returned, and trailing null fields are not suppressed.”

Now, while I can somewhat understand this behavior, it is certainly in opposition with regards to the behavior of the split function in other languages that I’ve used.  Ruby’s default behavior can cause serious problems when parsing CSV files and auto-populating fields where you expect empty strings rather than nils.

Which brings up the next point:




When I index outside of the array length, no exception is thrown.  Come on, Ruby!  That’s just bad form.  Again, the Ruby documentation for array says:

To raise an error for indices outside of the array bounds or else to provide a default value when that happens, you can use fetch.




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s