I’m back from vacation. After visiting my family in Long Island, we ventured up to the Catskills for a few nights, which culminated with my younger sister getting married. It was a very cool wedding! The next day, my wife, nephew, and I drove up to Montreal to see her folks. Montreal is one of my favorite cities (in the summer) – it has very European feel. As great as it is to get away, it’s always hard to get back into the groove after a trip. I’m just getting my sea legs back under me so this post is going to be short and sweet.
Have you ever needed to get rid of leading and trailing whitespace from a string? It’s a good rule of thumb to do just that to any input you’re receiving on a form. Luckily, it’s quite easy in most languages. Let’s take a look at how we’ll approach this in Ruby first.
str = " How's it going? " => " How's it going? " # Let's get rid of that whitespace str.strip() => "How's it going?" str => " How's it going? " # We didn't permanently change the string itself # Most methods are non-destructive, but Ruby let's us be destructive if we # really want to. We just got to bang it (pun intended) str.strip!() "How's it going?" str => "How's it going?"
str = " Trim me " str.object_id => 70365544319940 str.strip!() => "Trim me" str.object_id => 70365544319940 # Even though we changed the string, the id is still the same # We can also change characters in place, which cannot be done in JS str = '!' => '!' str => "Trim me!" # Pretty cool! str.object_id => 70365544319940 # No change
Thanks Wikipedia! Until next time! Cheers:)