Today I Learned

A Zero One initiative

`[]` 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!

Looking for help? Each developer at Zero One has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.