The Ruby Programming Language

Blocks and Iterators

#EVERY method takes a optional block as its last argument.

#A block is either a function 
['paul', 'john', 'ringo', 'george'].each do 
  puts 'hi'
end

#Or, if it starts with |x| then x iterates:
['paul', 'john', 'ringo', 'george'].each do 
  |x| puts x
end

# the same thing, but with {}
['paul', 'john', 'ringo', 'george'].each { |x| puts x }


#You use these for iterators

class Grades

  # *grades will mash up all arguments into an array.
  def initialize (*grades)
    @grades = grades
  end

  #This method takes no argument BUT
  # like all methods takes an optional block argument
  # at the end (block is ALWAYS the last argument).
  def hiToEach ()
    @grades.length.times do
      yield #calls the block.
    end
  end

  #This time pass the block a value (i). This method is thus an iterator
  def eachGrade()
    @grades.each do |i|
      yield(i)
    end
  end

  #Of course, the iterator can take arguments
  def eachBiggerThan(x)
    if block_given? #use this to check if we are given a block
      @grades.each do |i|
        yield(i) if (i >= x)
      end
    else
      puts "You forgot the block!"
    end
  end

end

g = Grades.new(88,99,80,77,87)

g.hiToEach {puts "hi"} #prints "hi" 5 times

#Use the iterator. Notice that this block starts with |x|
#Prints out: 105.6 118.8 96.0 92.4 104.4
g.eachGrade do |x|
  puts x * 1.2     
end

#Prints out 88 99 87
g.eachBiggerThan(85) do |x|
  puts x  
end

g.eachBiggerThan(85) # You forgot the block!


José M. Vidal .

8 of 11