2007 February 16 * Back to archives

String Includes Enumerable

While working on a little side project, I’m using Rails app to do a lot of system calls and grabbing the response of STDOUT or STDERR. One of the things that has made this really easy is that in Ruby, String includes the Enumerable module, which treats the string as an array. This may not be a surprise, except that each item is separated out in the array by a new line character “\n”. This allows the usage of the “each” method and all 28 other methods that come with Enumerable objects.

def rake
  @rake = `rake -T`
  @tasks = []
  @rake.sort.each { |line|
    @tasks << line.gsub("rake", "")
  }
end

If you want to iterate over the string character by character then you would have to iterate by byte and show the character value (the each_byte method returns the ASCII character number for the given character. You might do something like this to change all “a” characters to “e” characters:

@rake.each_byte do |b|
  b.chr.gsub(/a/,"e")
end
<span class="vi">@rake</span><span class="o">.</span><span class="n">each_byte</span> <span class="k">do</span> <span class="o">|</span><span class="n">b</span><span class="o">|</span>
  <span class="n">b</span><span class="o">.</span><span class="n">chr</span><span class="o">.</span><span class="n">gsub</span><span class="p">(</span><span class="sr">/a/</span><span class="p">,</span><span class="s2">&quot;e&quot;</span><span class="p">)</span>
<span class="k">end</span>

In Rails, there’s a method called chars"
which does some cool things by proxying your string to UTF-8-safe characters.

UPDATED: Dan Manges pointed out that I had a nonsensical example for each_byte.