Day 3 is all about strings, arrays, hashes, and ranges –
In Ruby, strings can be treated like arrays. Meaning it’s super easy to access substring. For example:
# returns ‘today’
theString = "It's raining today"
Finally, I always thought substr() methods were an awkward solution for something so common.
Replacing substrings is just as easy:
# theString is now “it’s raining still”
theString["today"] = "still"
All this talk about strings reminds me, Ruby knows the alphabet. Makes me smile just thinking about it.
"a".next # returns “b”
I’ve written a couple plugins (WP-CaTT, WP-iCal) for WordPress. Developing each one of them has sent me digging through PHP’s function list more frequently than I’d like – looking for just the right function. I’ve rewritten Perl apps in PHP to make the more readable and maintainable. As I’m learning more about the Ruby syntax, PHP feels like Perl.
Here’s a Super Useful Thing: Ruby can grep arrays. Need the list of months you can eat mussels in, if months_in_year was an array of months, this would work:
months_in_year.grep(/r/) # returns all months with an “r” in their name
I’d like to thank Slagell for explaining the difference between arrays and hashes in a useful way.
Back in day one, we talked about the Principle of Least Surprise. So far, getting through the end-of-chapter exercises has been a matter of applying that principle.
I was scanning the pages in today’s chapter looking for the method to flatten an array. According to the Principle of Least Surprise the method would be ‘flatten’. It is. 🙂