From: Josh Cheek on
[Note: parts of this message were removed to make it a legal post.]

On Mon, Mar 29, 2010 at 4:26 AM, Walle Wallen <walle.sthlm(a)gmail.com> wrote:

> I have done it many times before, but this time I can't get it too work.
> I'm starting to get a bit frustrating.
> So, I'm trying to sum all elements from the second element in a Array
> using inject. The problem is that inject returns nil every time. What am
> I doing wrong?
>
> parameters.each {|element| print element + ","} --> ?faq,using,rtorrent
> parameters.each {|element| print element.class.to_s + ","} -->
> String,String,String
> parameters.class --> Array
>
> Doesn't work.
> (parameters[1]..parameters[-1]).inject {|result, element| result +
> element} --> nil
> Neither does.
> (parameters[1]..parameters[-1]).to_a.inject {|result, element| result +
> element} --> nil
>
> //Walle
> --
> Posted via http://www.ruby-forum.com/.
>
>
Rails has this by default:
http://api.rubyonrails.org/classes/Enumerable.html#M002571

module Enumerable
def sum(identity = 0, &block)
return identity unless size > 0

if block_given?
map(&block).sum
else
inject { |sum, element| sum + element }
end
end
end

['a','b','c'].sum # => "abc"
[1,2,3].sum # => 6
[[0],['0'],[:'0'],[/0/]].sum # => [0, "0", :"0", /0/]
[].sum(/abc/) # => /abc/
[1,2,3].sum(/abc/) # => 6
['a','b','c'].sum(&:upcase) # => "ABC"

That last one is 1.9 only (or another monkey patch ;P )

From: Rick DeNatale on
2010/3/29 Jesús Gabriel y Galán <jgabrielygalan(a)gmail.com>:
> On Mon, Mar 29, 2010 at 12:39 PM, Walle Wallen <walle.sthlm(a)gmail.com> wrote:

> In your original example, the words were quite far apart:
>
> irb(main):005:0> ("faq".."rtorrent").each_with_index {|s, i| p s;
> break if i > 20}


Actually in his original example parameters appears to be ["?faq" ,
"using" , "rtorrent"]

so

(parameters[1]..parameters[-1])

is

("using".."rtorrent")

and since "using" > "rtorrent" the range is empty which is why inject
returns nil.



--
Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale