tags:

views:

103

answers:

3

I was reading a Ruby question about the .each iterator, and someone stated that using .each can be a code smell if higher order iterators are better suited for the task. What are higher order iterators in Ruby?

edit: Jörg W Mittag, the author of the StackOverflow answer that I was referring to mentioned that he meant to write higher level iterators, but he also explained what they are very well below.

+2  A: 

From the usual definition of "higer-order" I would say a higher-order iterator is an iterator which takes an iterator as an argument or returns an iterator. So something like enum_for maybe. However I don't think this is what the person meant.

I think the person meant iterators like map or select which are higher-order functions, but did not realize that each is of course also a higher-order function. So basically this is just a case of terminological confusion.

The point of the poster presumably was that you should not use each in cases where map, select or inject could naturally be used instead. And to make that point he used a term, that didn't really make sense in that context.

sepp2k
It's much simpler than that: I meant to write higher-*level*.
Jörg W Mittag
@Jörg: Well, if I had known that you were the person in question, I wouldn't have assumed that you misunderstood what higher-order meant ;-)
sepp2k
BTW: This is the post in question: http://StackOverflow.Com/questions/3493583/iterating-hash-collection/3493724/#3493724 . I obviously fixed the error since then.
Jörg W Mittag
+4  A: 

They're talking about more specialized methods such as map, filter or inject. For example, instead of this:

even_numbers = []
numbers.each {|num| even_numbers << num if num.even?}

You should do this:

even_numbers = numbers.select {|num| num.even?}

It says what you want to do but encapsulates all the irrelevant technical details in the select method. (And incidentally, in Ruby 1.8.7 or later, you can just write even_numbers = numbers.select(&:even?), so even more concise if slightly Perl-like.)

These aren't normally called "higher-order iterators," but whoever wrote that probably just had a minor mental mixup. It's a good principle whatever terminology you use.

Chuck
*whoever wrote that probably just had a minor mental mixup* -- Yes, I did :-)
Jörg W Mittag
BTW: This is the post in question: http://StackOverflow.Com/questions/3493583/iterating-hash-collection/3493724/#3493724 . I obviously fixed the error since then.
Jörg W Mittag
+8  A: 
Jörg W Mittag