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
-
#!/usr/bin/env ruby
-
-
class MyObject
-
attr_accessor :data
-
-
def initialize
-
@data = %w{maku chaku was here}
-
end
-
-
def simple_yield_example
-
puts "start"
-
yield
-
yield
-
puts "end"
-
end
-
-
def each
-
idx = 0
-
while idx < @data.length
-
yield @data[idx]
-
idx += 1
-
end
-
end
-
-
end
-
-
puts "##############"
-
MyObject.new.simple_yield_example { puts "Hello there!" }
-
-
puts "##############"
-
MyObject.new.each do |val|
-
puts val
-
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.








