All Geek to Me

July 29, 2009

Ruby Dangerous Method

Filed under: Geek Stuff — britinla @ 11:10 am

In Ruby method names ending with an exclamation mark are considered “dangerous” as they change the object on which the method is invoked.

I ran into a problem using one of these dangerous methods last night. I wanted to ensure that strings that I was handling were uppercase. There are two methods in Ruby that do this: upcase and upcase! I attempted to use the latter option. It worked on my first tests, but it failed when I passed a string that was already in uppercase and the string was changed to nil (empty string). This behaviour is explicitly documented, but I had missed that detail. Using the regular method, s=s.upcase works as I required, so it was a simple fix. However, this is an annoying difference in behaviour between the two method and seems to be counter- intuitive.

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.