I’m going through Beginning Ruby From Novice To Professional 2nd Edition and am currently on page 49 where we are learning about RegEx basics. Each RegEx snippet in the book has a code trailing it that hasn’t been explained.
{ |x| puts x }
In context:
"This is a test".scan(/[a-m]/) { |x| puts x }
Could someone please clue me in?
A method such as
scanis an iterator; in this case, each time the passed regex is matched,scandoes something programmer-specified. In Ruby, the “something” is expressed as a block, represented by{ code }ordo code end(with different precedences), which is passed as a special parameter to the method. A block may start with a list of parameters (and local variables), which is the|x|part;scaninvokes the block with the string it matched, which is bound toxinside the block. (This syntax comes from Smalltalk.)So, in this case,
scanwill invoke its block parameter every time/[a-m]/matches, which means on every character in the string betweenaandm.