Understanding Ruby, part III

Loops & Iterators

Ok, it’s been a long time since my last post, however I’ve been learning a lot about ruby including metaprogramming which is an exciting topic I hope to talk about later, but let’s keep going with this mini/quick tutorials to understand Ruby.

Last time I offered to talk about advance iterators, so let’s see some examples and then let's dissect them :)

1.upto(10) do |n|
  puts n
end
data.each do |x|
  puts x
end
5.times { puts 'hello world' }

There are a lot iterators so you can check ruby api which is the recommended approach. However let me give you some of the most valuable iterators I’ve found.

  • select: it returns an array with all elements for which the block returns a value different of false or nil
  • reject: the oposite of select
  • inject: it’s kind of complicated but it’s really useful, a good example can be:

    data = [1,3,5,7,9]
    max_value = data.inject do |x,y|
    # it will get the max value
      x > y ? m : x
    end

Every iterator is supported by yield, thanks to it iterators can bypass the associated block to be executed. Here’s something to notice:

…This may be confusing if you are used to languages like Java in which iterators are objects. In Java, the client code that uses the iterator is in control and pulls values from the iterator when it needs them. In Ruby, the iterator method is in control and pushes values to the block that wants them…

The Ruby Programming Language: David Flanagan, Yukihiro Matsumoto - 2008

;o)