Revisting Ruby – Array.each

I’ve been in love with Ruby for long now – and its only obvious that I should get serious about it.

Hence, I’ve decided to go through Programming Ruby 1.9 – a chapter a day.

Understanding Array.each and blocks

  1. #!/usr/bin/env ruby
  2.  
  3. class MyObject
  4.   attr_accessor :data
  5.  
  6.   def initialize
  7.     @data = %w{maku chaku was here}
  8.   end
  9.  
  10.   def simple_yield_example
  11.     puts "start"
  12.     yield
  13.     yield
  14.     puts "end"
  15.   end
  16.  
  17.   def each
  18.     idx = 0
  19.     while idx < @data.length
  20.       yield @data[idx]
  21.       idx += 1
  22.     end
  23.   end
  24.  
  25. end
  26.  
  27. puts "##############"
  28. MyObject.new.simple_yield_example { puts "Hello there!" }
  29.  
  30. puts "##############"
  31. MyObject.new.each do |val|
  32.   puts val
  33. end


Output

[makuchaku@Warrior ruby]$ ./each.rb
##############
start
Hello there!
Hello there!
end
##############
maku
chaku
was
here


Explanation

Objective was to implement a lookalike of “each” as as iterator. A code block, when associated with a method call can be called by the method by using “yield”. The number of variables being passed into each block should match the number of variables being passed into the yield.

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.