On Aug 12, 2006, at 3:22 PM, Leslie Viljoen wrote:

> 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?

I used the parens to split the arguments, as you can in Ruby  
assignments.

> 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)

This expression uses inject's default behavior to setup sum, but  
remember that elements are now paired with their index.  sum is thus  
initialized to [1, 0], which blows up your later math.  You can fix  
this by initializing sum yourself:

[1,3,5].inject_with_index(0) {|sum, (part, index)| sum + part}

James Edward Gray II