Daniel Pietzsch

Personal blog. Mostly photos.

next can return a value

Iterating through an array, I found myself wanting to collect an element as-is most times, and only in certain conditions modify the original element and collect the modification instead. So, I used next with a parameter to skip an element quickly and move on to the next one. And that parameter will be returned and still be collected.

Much simplified example:

[1,2,3,4,5,6].collect do |n|
  next n if n%2 == 1
  n*n
end  
#=> [1, 4, 3, 16, 5, 36]