by simon baird

Thursday, February 23, 2006

My first Ruby hack - Array.each_with_count

I've started to learn Ruby. It is very cool. You can try it out now in your browser. I'm currently trying to use it instead of (my old faithful) Perl for little text manipulation scripts. Here is a little thing I put together because I was doing this kind of thing a lot:
count = 0
some_array.each do |v|
  # do stuff requiring count
  count += 1
end
It's an extended each iterator for arrays that includes a built in counter. Here it is:
class Array
  def each_with_count
    count = 0
    self.each do |element|
      yield element,count
      count += 1
    end
  end
end
Example usage of my new iterator:
["abc","def",123].each_with_count do |x,i|
  print i,"\t",x,"\n"
end
Which of course prints this:
0       abc
1       def
2       123
Cool huh?! (Apologies to my non computer geek readers... :)

Update 10-Mar-06

Oh boy do I feel foolish! My next project is a roundish thing that might have some application in the field of transport. :) See Enumerable#each_with_index. Ps, ruby is good.

1 comment:

scott said...

Thanks for the apology. ;-)