`[]` is smarter thank you think!
You’re probably very familiar with using []
on objects which are enumerable, but []
has a few more tricks up it’s sleeve when it comes to strings which you may not know about:
string = "Ruby is a cool language"
Did you know that you can use []
to fetch a substring from a string, and return nil
if it doesn’t exist?
string["cool lang"] # => "cool lang"
string["foo"] # => nil
You can even throw a Regex in that bad boy and you’re off to the Regex races!
And for the final trick we’ll make a pesky substring DISAPPEAR!
string["cool"] = "great" # => "great"
string # => "Ruby is a great language"
Next time you’re munging with strings, remember that []
is smarter than you think!