Ruby - Iteration with a regular expression

Introduction

To iterate through a string and have access to each section of it separately, use scan iterator method:

Demo

"test".scan(/./) { |letter| puts letter }

Result

scan method scans through the string looking for anything that matches the regular expression passed to it.

Here, the regular expression looks for a single character at a time.

Each letter is fed to the block, assigned to letter, and printed to the screen.

Demo

"This is a test".scan(/../) { |x| puts x }

Result

Here, you're scanning for two characters at a time.

Related Topic