How to make iterator methods in Ruby.

Most of us strictly rails developers don’t know how to make iterator methods (i.e. methods that accept blocks). For example, say you wanted to make a method to reverse each word in a string – not the entire string but each individual word. You could write this method:

class String
  def reverse_each_word
    self.split.collect { |word| word.reverse }
  end
end

That works but suppose you wanted to abstract this logic to use elsewhere. So instead let’s write a method to iterate through each word in the sentence, yielding the result to a block. Then you can do whatever you want to each word (upcase, reverse, length, capitalize, etc). Now that’s a bit trickier:

class String
  def each_word
    self.split.each { |word| yield word }
  end
end

And now you have a more flexible method which can do things like this:

"This is a very short sample string".each_word do |word|
  word.reverse.upcase
end

Neat. But what’s going on here? The reverse_each_word method is pretty vanilla – take a string, split the words into an array, reverse them, and return the collection. The each_word method, however, is less straight forward. It starts out much the same – take a string, split the words into an array but then…

Well, it’s actually pretty simple. We use the keyword yield to let ruby know that our method is going to accept a block. And, more specifically, we’re telling ruby we’d like each word in our array to be yielded as parameters within that block. Now we can iterate through through each of our words – manipulating them however we please.

Tags: ,

2 Comments

Your thoughts?

Preview