Fork me on GitHub

Project Notes

#163 Expressions and String Indexes

When string indexes are better than regex, and when regex can help writing a string index.

Notes

The ruby String class overloads the [] operator with some interesting behaviours:

string[index] → new_string or nilclick to toggle source
string[start, length] → new_string or nil
string[range] → new_string or nil
string[regexp, capture = 0] → new_string or nil
string[substring] → new_string or nil

Using string[substring] is a more efficient way of testing for substring than a regular expression

text = 'Plant a memory, plant a tree, do it today for tomorrow.'
# ok
text =~ /memory/
# better
text['memory']

Using Regular Expressions as String Indexes

Using string[regexp, capture = 0] syntax allows matching and replacement in a string with a very simple syntax.

Getting content of a match:

text = 'Plant a memory, plant a tree, do it today for tomorrow.'
text[/pl.*ee/]
=> 'plant a tree'

Getting content of a captured group:

text = 'Plant a memory, plant a tree, do it today for tomorrow.'
text[/it\s(\w+)/, 1]
=> 'today'

Replacing content of a captured group:

text = 'Plant a memory, plant a tree, do it today for tomorrow.'
text[/it\s(\w+)/, 1] = 'now'
text
=> 'Plant a memory, plant a tree, do it now for tomorrow.'

Running the Examples

See examples.rb; these demonstrations are written asa test suite:

$ ruby examples.rb
Run options: --seed 63700

# Running:

....

Finished in 0.001045s, 3827.7510 runs/s, 3827.7510 assertions/s.

4 runs, 4 assertions, 0 failures, 0 errors, 0 skips

Credits and References

About LCK#163 ruby
Project Source on GitHub Return to the Project Catalog

LittleCodingKata is my collection of programming exercises, research and code toys broadly spanning things that relate to programming and software development (languages, frameworks and tools).

These range from the trivial to the complex and serious. Many are inspired by existing work and I'll note credits and references where applicable. The focus is quite scattered, as I variously work on things new and important in the moment, or go back to revisit things from the past.

This is primarily a personal collection for my own edification and learning, but anyone who stumbles by is welcome to borrow, steal or reference the work here. And if you spot errors or issues I'd really appreciate some feedback - create an issue, send me an email or even send a pull-request.

LittleArduinoProjects LittleModelArt More on my blog