Flowdock

Notes posted by svoop

RSS feed
March 8, 2010
0 thanks

Eagerness

Check out this simple example:

"Hello Ruby friend".sub(/^(.*)e/,  'X')  # => "Xnd"
"Hello Ruby friend".sub(/^(.*?)e/, 'X')  # => "Xllo Ruby friend"

The question mark turns the dotstar into non-eager mode which means it will halt on the first subsequent “e” rather than the last one. This comes in handy e.g. for Cucumber step definitions.

Okay, but not really nice:

/^I am using rvm "([^\"]*)" with gemset "(.*)"$/

Much more readable and consistent equivalent to the above:

/^I am using rvm "(.*?)" with gemset "(.*?)"$/
November 11, 2009
2 thanks

Re: Taking care when writing regex

Oleg’s example from above contains an error and a pitfall:

validates_format_of :something => /^\w$/

The string “blahblahblah” doesn’t pass this validation. What Oleg ment is rather a continuous string of at least one alphanumeric character:

validates_format_of :something => /^\w+$/

However, that’s no good neither because it contains a well hidden trap in case you are validating content from a textarea.

Ruby (both 1.8 and 1.9) always matches ^ and $ against the beginning and ending of lines and not the entire string. Thus “First linenSecond line” will pass the above validation although it’s clearly not a continuous string.

You should use A (replacement for ^) and z (replacement for $) instead as their scope is the entire string:

validates_format_of :something => /\A\w+\z/

(A side note for those with a Perl background: Please note that the “s” modifier has a different meaning in Ruby and won’t do the trick here.)

October 30, 2009
2 thanks

Map-like Manipulation of Hash Values

Let’s say you want to multiply all values of the following hash by 2:

hash = { :a => 1, :b => 2, :c => 3 }

You can’t use map to do so:

hash.map {|k, v| v*2 }   # => [6, 2, 4]

However, with merge you can:

hash.merge(hash) {|k,v| v*2 }   => {:c=>6, :a=>2, :b=>4}

(The above is Ruby 1.8, in Ruby 1.9 the order is preserved.)

February 10, 2009
0 thanks

Cheat Sheet

I have written a short introduction and a colorful cheat sheet for Perl Compatible Regular Expressions (PCRE) as used by Ruby’s Regexp class:

http://www.bitcetera.com/en/techblog/2008/04/01/regex-in-a-nutshell/

February 10, 2009
0 thanks

Cheat Sheet

I have written a short introduction and a colorful cheat sheet for Perl Compatible Regular Expressions (PCRE) as used by Ruby’s Regexp class:

http://www.bitcetera.com/en/techblog/2008/04/01/regex-in-a-nutshell/

February 10, 2009
3 thanks

Cheat Sheet

I have written a short introduction and a colorful cheat sheet for Perl Compatible Regular Expressions (PCRE) as used by Ruby’s Regexp class:

http://www.bitcetera.com/en/techblog/2008/04/01/regex-in-a-nutshell/