fsteeg.com | notes | tags

∞ /notes/ruby-iterators | 2005-10-13 | ruby

Ruby iterators

Cross-posted to: https://fsteeg.wordpress.com/2005/10/13/ruby-iterator/

An example for the higher-level, more problem-oriented things you can do with Ruby's iterators. In Java, I just tried to do this to insert blanks into all words written entirely in uppercase:

s.replaceAll("\\b([A-Z]+)\\b","$1".replaceAll("([A-Z])","$1"+" "));

Of course it didn't work, because the second replaceAll is called on "$1" before "$1" is replaced with a match.

In Ruby such a thing is possible using iterators:

s.gsub(/\b([A-Z]+)\b/){$1.gsub(/([A-Z])/){$1+" "}}

It could be even done simpler, with only one regex and iterator involved, plus this solution has no trailing space:

s.gsub(/\b([A-Z]+)\b/){$1.split("").join(" ")}