Trying to sum from an array
Suppose it gets
returns
s = "21 14 7"
Then use Array # sum (new in Ruby v.2.4.0):
puts s.split.sum(&:to_i)
42
or use Enumerable # reduce (aka inject
available from the start)
puts s.split.reduce(0) { |t,ss| t+ss.to_i }
42
source to share
Although the accepted answer is correct, but only for an array with 2 elements (even for an array with 1 element, it will break). What if the size of the array is variable? Ruby has more general ways to do this.
You can use method reduce
or inject
documentation
example code:
a = gets.split(" ").map! {|n| n.to_i}
puts a.reduce(:+)
If I enter 1 2 3 4 5 6 7
then it will output28
How reduce
can you use
a = gets.split(" ").map! {|n| n.to_i}
puts a.inject(:+)
Hope this helps someone.
source to share
one-liner with Enumberable # map and Enumberable # reduce
gets.split.map(&:to_i).reduce(:+)
source to share