Working with Ruby
Hi, I am Jan. This is my old Ruby blog. I still post about Ruby, but I now do it on idiosyncratic-ruby.com. You should also install Irbtools to improve your IRB.

Small Ruby CLI Improvements (Part 1): Command-line Regex Debugging

This little method (now also available in zucker/debug) is useful for understanding and creating regexes:

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Regexp
  def visualize(string, groups = nil)
    if self =~ string
      if !groups
        puts $` + ' >' + $& + '< ' + $'
      else
        Array( groups ).each{ |group|
          begin
            gr_string = string.dup
            gr_string[ $~.end( group ),   0 ] = '< '
            gr_string[ $~.begin( group ), 0 ] = ' >'
            puts group.to_s + ': ' + gr_string
          rescue IndexError
            puts group.to_s + ': no match'
          end
        }
      end
    else
      puts 'no match'
    end

    nil
  end

  alias vis visualize
end

And here is how to use it with an example regex = /\b([A-Z0-9._%+-]+)@([A-Z0-9.-]+\.[A-Z]{2,4})\b/i which can be used to get 99% of all e-mail adresses:

>> regex.vis 'I do not contain an email address.'
no match
=> nil
>> regex.vis 'I contain an email address: mail@example.com'
I contain an email address:  >mail@example.com<
=> nil
>> regex.vis 'mail@example.com', 1
1:  >mail< @example.com
=> nil
>> regex.vis 'mail@example.com', 2
2: mail@ >example.com<
=> nil
>> regex.vis 'mail@example.com', 3
3: no match
=> nil
>> regex.vis 'mail@example.com', [0,1,2]
0:  >mail@example.com<
1:  >mail< @example.com
2: mail@ >example.com<
=> nil
Creative Commons License