Category:Ruby’

Ruby Inside

 - by joerg

Just installed wp-syntax plugin and pasted code from rubyinside.com to demonstrate the syntax highlighting. The author of the following code is writer of the book Beginning Ruby.

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.”

2 – Shortcut for Array#join

It’s common knowledge that Array#*, when supplied with a number, multiplies the size of the array by using duplicate elements:

[1, 2, 3] * 3 == [1, 2, 3, 1, 2, 3, 1, 2, 3]

It’s not well known, however, that when given a string as an argument Array#* does a join!

%w{this is a test} * ", "                 # => "this, is, a, test"
h = { :name => "Fred", :age => 77 }
h.map { |i| i * "=" } * "\n"              # => "age=77\nname=Fred"

4th edition

 - by joerg

The pragamatic bookshelf is advertising its upcoming 4th editon of Agile Web Development with Rails. A preview of the complete refactoring for rails 3 is already available in a beta licence program.