[#1026] Is this a bug? — Dave Thomas <Dave@...>

18 messages 2000/01/03

[#1084] Infinite loop — Dave Thomas <Dave@...>

17 messages 2000/01/11

[#1104] The value of while... — Dave Thomas <Dave@...>

24 messages 2000/01/11

[ruby-talk:01047] Re: Equivalent of 'inject'

From: matz@... (Yukihiro Matsumoto)
Date: 2000-01-04 04:09:31 UTC
List: ruby-talk #1047
Hi,

In message "[ruby-talk:01046] Equivalent of 'inject'"
    on 00/01/03, Dave Thomas <Dave@thomases.com> writes:

|Now I know I'm being stupid, but I can't see a Ruby equivalent of
|operations such as Smalltalk's 'inject'. What's the clean way of (say) 
|summing the elements in an array?

If I remember correctly, inject works like this, right?

  array.inject(0){|n,x| n+x}  # => sum of the array

If so, Ruby does not have equivalent built-in.

  n = 0
  for x in array
    n += x
  end

will do the thing you want.

In addition, you can always add the feature you want to Ruby by
yourself.  With the following code, inject will be added to all
enumerable objects (Array, Hash, etc.).

  module Enumerable
    def inject(n)
      self.each{|x| n = yield(n, x)}
      return n
    end
  end

Hope this helps
							matz.

In This Thread

Prev Next