How to add odd_or_even automatically in the for loop

When you need to distinguish between odd or even elements in Ruby loop, you can use for example ActiveSupport cycle helper. When you need to do it in some simple scripting tool it might be unnecessary. Without cycle helper you can extend Array class and add enumarable method – lets call it each_with_index_parity.

Method implementation can look like that below:

 class Array def each_with_index_parity self.each_with_index do |entry, index| yield(entry, index, index % 2 == 0 ? :even : :odd) end end end 

Now it is possible to do something like that:

 @records = ('a'..'z').to_a @records.each_with_index_parity do |el, index, parity| puts "#{el} #{index} #{parity}" end 

That works fine for me.

There are many way to manage with that problem. If you don’t want for some reason define methods in builtin class (in that case in Array class) you can use iterate in loop using each_with_index. For example like that:

 @records = ('a'..'z').to_a @records.each_with_index do |el, index| parity = index.even? ? :even : :odd puts "#{el} #{index} #{parity}" end 

In that case you need to calculate parity in loop code.

Comments

wrote

Woah nelly, how about them apepls!

Grizzly

Grizzly wrote

I thhougt I'd have to read a book for a discovery like this!

Jonnie

Jonnie wrote

I'm grfateul you made the post. It's cleared the air for me.

Comment