2 Replies - 598 Views - Last Post: 16 May 2013 - 08:48 PM Rate Topic: -----

#1 Btu  Icon User is offline

  • D.I.C Regular

Reputation: 36
  • View blog
  • Posts: 250
  • Joined: 16-May 11

regexp code block

Posted 16 May 2013 - 07:34 PM

Cone someone help meunderstand this code:

def test_sub_is_like_find_and_replace
    assert_equal "one t-three", "one two-three".sub(/(t\w*)/) { $1[0, 1] }
  end



I know what assert_equal means, and I understand that I'm calling the sub method on that string object with a regular expression but this confuses me:
{ $1[0, 1] }



Thanks in advance!

Is This A Good Question/Topic? 1
  • +

Replies To: regexp code block

#2 xclite  Icon User is offline

  • LIKE A BOSS
  • member icon


Reputation: 905
  • View blog
  • Posts: 3,167
  • Joined: 12-May 09

Re: regexp code block

Posted 16 May 2013 - 08:37 PM

It's using grouping. The (t\w*) creates a group around the t character followed by any number of word characters (so it matches "two", stopping before '-' which does not match the regexp).

The block returns something based on that grouping - $1 is a "magic variable" that stores the first match. That string is "two". it's then returning "two"[0, 1], which if you plug into irb should be "t".

Basically sub is performing the match and then using the block to return a value based on that match.
Was This Post Helpful? 3
  • +
  • -

#3 Btu  Icon User is offline

  • D.I.C Regular

Reputation: 36
  • View blog
  • Posts: 250
  • Joined: 16-May 11

Re: regexp code block

Posted 16 May 2013 - 08:48 PM

This is great info, thanks a lot!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1