Trying to sum from an array

    a = gets.split(" ").each {|n| n.to_i}
    puts "#{a[0] + a[1]}"

      

Let's say I entered 1 2 in the above code. The output will be 12. How to make a simple addition using this code? For pin 3

+3


source to share


4 answers


each

will not change the array. You must usemap!



a = gets.split(" ").map! {|n| n.to_i}
puts "#{a[0] + a[1]}"

      

+2


source


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

      

+2


source


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.

+1


source


one-liner with Enumberable # map and Enumberable # reduce

gets.split.map(&:to_i).reduce(:+)

      

0


source







All Articles