Archive for October 18th, 2010

21 Ruby Tricks You Should Be Using In Your Own Code

21 Ruby Tricks You Should Be Using In Your Own Code.

Writing for Ruby Inside, I get to see a lot of Ruby code. Most is good, but sometimes we forget some of Ruby’s shortcuts and tricks and reinvent the wheel instead. In this post I present 21 different Ruby “tricks,” from those that most experienced developers use every day to the more obscure. Whatever your level, a refresh may help you the next time you encounter certain coding scenarios.

Note to beginners: If you’re still learning Ruby, check out my Beginning Ruby book.

1 – Extract regular expression matches quickly

A typical way to extract data from text using a regular expression is to use the match method. There is a shortcut, however, that can take the pain out of the process:

email = "Fred Bloggs <fred@bloggs.com>"
email.match(/<(.*?)>/)[1]            # => "fred@bloggs.com"
email[/<(.*?)>/, 1]                  # => "fred@bloggs.com"
email.match(/(x)/)[1]                # => NoMethodError [:(]
email[/(x)/, 1]                      # => nil
email[/([bcd]).*?([fgh])/, 2]        # => "g"

Ultimately, using the String#[] approach is cleaner though it might seem more “magic” to you. It’s also possible to use it without including an extra argument if you just want to match the entire regular expression. For example:

x = 'this is a test'
x[/[aeiou].+?[aeiou]/]    # => 'is i'

In this example, we match the first example of “a vowel, some other characters, then another vowel.”