Day 3 is all about strings, arrays, hashes, and ranges – abstract, geeky terms for buckets
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"
theString[13, 5]
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. 🙂
This post documents my journey through Sam’s Teach Yourself Ruby in 21 days. I’ll be joining Al Abut in his effort to learn Ruby and blog along the way.
Regarding String#[]:
It can also take a Regexp which is basically super cool. Say you want to match some kind of HTML tag: “foo bar qux“[/<(w+)>/, 1] would give you “em”.
Want to replace? That’s just as easy:
“My name is nice.”[/My (w+) is (w+)/, 1] = “language” # => “My language is nice.”
“My name is nice.”[/My (w+) is (w+)/, 2] = “a secret” # => “My name is a secret.”
Regarding Enumerable#grep:
You can use anything that implements the === method. (The thing used in case-when constructs.)
[“foo”, 3, “bar”, 100, “qux”, 90].grep(String) # => [“foo”, “bar”, “qux”]
[“foo”, 3, “bar”, 100, “qux”, 90].grep(Numeric) # => [3, 100, 90]
[3, 1, 4, 1, 5, 9].grep(3 .. 9) # => [3, 4, 5, 9]
By now you will probably know why so many people love this language. 🙂