I’m working my way through The Ruby Course slides at the moment and am
on the section about dynamicity. Specifically I’m on slide 59 right
now, the slide about a ListItem – essentially a link list.
So, this got me thinking: what makes a good #each method? I’d love to
hear any pearls of wisdom if any of you have the time.
So, this got me thinking: what makes a good #each method? I’d love to
hear any pearls of wisdom if any of you have the time.
I think an each method should have the following properties
All elements must be yielded
Each element must be yielded exactly once
If the container has some order associated with it (ie Array or
SortedSet) the elements should be yielded in order
If there is more than ordering (such as a post, pre or in order
walk round a binary tree) then the elements should be yielded
according to the ordering that is as closest to ‘natural’ ordering
(inorder in the case of a binary tree). each methods for the other
orderings (each_preorder, each_postorder) must also be provided.
That’s my opinion, I’m sure other people might disagree with me here.
I’m a little confused by this. As I understand it, “arity” is the
number of arguments to a term. Perhaps I’m just not seeing it in your
example, but where does arity fit into it? Doubly, why might one want
to know this?
Concerning ordered elements, what is the best way to ascertain the
order wherein the structure is not an array? For instance, suppose you
had a link list. You could have a class variable that kept track of
the beginning, but this would mean difficulties when you had more than
one link list in play.
In trying to solve the order issue (naively), I wrote a method like:
def each(&block)
current = self.previous
until current.previous.nil?
current = current.previous
end
…
end
This obviously doesn’t work because on each call of #each, the focus is
rewound to the intial element in the list.
I’ve had a few people write me asking about the Ruby Course slides.
Not that I mind replying to each of you, but I thought I’d save the
curious a little time =)
All sorts of Ruby articles and documents can be found at the Ruby Doc
website: http://www.ruby-doc.org
The slides in particular are found here (NB this is a direct link to a
PDF and may at some point change):
Enjoy!
James H.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.