Leslie Viljoen
8/12/2006 8:23:00 PM
On 8/12/06, Leslie Viljoen <leslieviljoen@gmail.com> wrote:
> On 8/12/06, James Edward Gray II <james@grayproductions.net> wrote:
> > Hope this helps:
> >
> > >> require "enumerator"
> > => true
> > >> module Enumerable
> > >> def inject_with_index(*args, &block)
> > >> enum_for(:each_with_index).inject(*args, &block)
> > >> end
> > >> end
> > => nil
> > >> ("A".."D").inject_with_index("") do |str, (let, i)|
> > ?> i % 2 == 0 ? str += let : str
> > >> end
> > => "AC"
What I don't understand about your solution is the "do |str, (let, i)|",
how can you have brackets in there? What does that do?
Your example works as above but I can't get it to work with an array.
Here's what I get:
p [1,3,5].inject_with_index{|sum, (part, index)| sum + part}
=> seconderc.rb:46:in `+': can't convert Fixnum into Array (TypeError)
p [1,3,5].inject_with_index{|sum, part, index| sum + part}
=> [1, 0, 3, 1, 5, 2]
My own inject is a lot clunkier (and takes no params) but seems to work:
def inject_with_index
total = self[0]
index = 1
loop do
break if index == self.length
total = yield(total, self[index], index)
index += 1
end
total
end
public :inject_with_index
p [1,3,5].inject_with_index{|sum, part, index| sum + part}
=> 9
Les