Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 269 Vote(s) - 3.48 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to sum array of numbers in Ruby?

#1
I have an array of integers.

For example:

array = [123,321,12389]

Is there any nice way to get the sum of them?

I know, that

sum = 0
array.each { |a| sum+=a }


would work.
Reply

#2
Alternatively (just for comparison), if you have Rails installed (actually just ActiveSupport):

require 'activesupport'
array.sum

Reply

#3
ruby 1.8.7 way is the following:

array.inject(0, &:+)
Reply

#4
Also allows for `[1,2].sum{|x| x * 2 } == 6`:

#

[To see links please register here]

class Array
def sum(method = nil, &block)
if block_given?
raise ArgumentError, "You cannot pass a block and a method!" if method
inject(0) { |sum, i| sum + yield(i) }
elsif method
inject(0) { |sum, i| sum + i.send(method) }
else
inject(0) { |sum, i| sum + i }
end
end
end
Reply

#5
Just for the sake of diversity, you can also do this if your array is not an array of numbers, but rather an array of objects that have properties that are numbers (e.g. amount):

array.inject(0){|sum,x| sum + x.amount}
Reply

#6
You can also do it in easy way

def sum(numbers)
return 0 if numbers.length < 1
result = 0
numbers.each { |num| result += num }
result
end


Reply

#7
You can use *.map* and *.sum* like:

array.map { |e| e }.sum
Reply

#8
array.reduce(0, :+)

While equivalent to `array.inject(0, :+)`, the term **reduce** is entering a more common vernacular with the rise of [MapReduce programming models][1].

**inject**, **reduce**, **fold**, **accumulate**, and **compress** are all synonymous as a class of [folding functions][2]. I find consistency across your code base most important, but since various communities tend to prefer one word over another, it’s nonetheless useful to know the alternatives.

To emphasize the map-reduce verbiage, here’s a version that is a little bit more forgiving on what ends up in that array.

array.map(&:to_i).reduce(0, :+)

Some additional relevant reading:

-

[To see links please register here]

-

[To see links please register here]

-

[To see links please register here]



[1]:

[To see links please register here]

[2]:

[To see links please register here]

Reply

#9
Ruby 2.4.0 is released, and it has an [Enumerable#sum][1] method. So you can do

array.sum

Examples from the docs:

{ 1 => 10, 2 => 20 }.sum {|k, v| k * v } #=> 50
(1..10).sum #=> 55
(1..10).sum {|v| v * 2 } #=> 110


[1]:

[To see links please register here]

Reply

#10
# New for Ruby 2.4.0

You can use the aptly named method `Enumerable#sum`. It has a lot of advantages over `inject(:+)` but there are some important notes to read at the end as well.

## Examples

### Ranges

(1..100).sum
#=> 5050

### Arrays

[1, 2, 4, 9, 2, 3].sum
#=> 21

[1.9, 6.3, 20.3, 49.2].sum
#=> 77.7

## Important note
This method is not equivalent to `#inject(:+)`. For example

%w(a b c).inject(:+)
#=> "abc"
%w(a b c).sum
#=> TypeError: String can't be coerced into Integer

Also,


(1..1000000000).sum
#=> 500000000500000000 (execution time: less than 1s)
(1..1000000000).inject(:+)
#=> 500000000500000000 (execution time: upwards of a minute)

See [this answer](

[To see links please register here]

) for more information on why `sum` is like this.

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through