I think that Samuel meant a method that would convert
[1, 2, 3, 4]
into
[[1, :first], [2, :middle], [3, :middle], [4, :last]]
What do you do in case the collection just has one element?
If that's the case then I think it can be easily implemented with
#each_with_index without defining it on Enumerable:
def with_position(enumerable)
enumerable.each_with_index.map do |item, index|
[
item,
case index
when 0 then :first
when enumerable.length - 1 then :last
That does not work for all Enumerables, because you cannot expect
#length to be implemented. The contract only requires method #each be
implemented. Your code needs to be more complex. Something like:
module Enumerable
def each_with_label
return to_enum(:each_with_label) unless block_given?
count = 0
item = nil
each do |e|
yield item, count == 1 ? :first : :middle if count > 0
count += 1
item = e
end
case count
when 0
# nothing
when 1
yield item, :first
else
yield item, :last
end
self
end
end
irb(main):001:0> 5.times.each_with_label.to_a
=> [[0, :first], [1, :middle], [2, :middle], [3, :middle], [4, :last]]
irb(main):002:0> 3.times.each_with_label.to_a
=> [[0, :first], [1, :middle], [2, :last]]
irb(main):003:0> 2.times.each_with_label.to_a
=> [[0, :first], [1, :last]]
irb(main):004:0> 1.times.each_with_label.to_a
=> [[0, :first]]
else :middle
end
]
end
end
Cheers
robert
···
On Tue, Sep 15, 2015 at 3:51 PM, Greg Navis <contact@gregnavis.com> wrote:
--
[guy, jim, charlie].each {|him| remember.him do |as, often| as.you_can
- without end}
http://blog.rubybestpractices.com/