Reputation: 219
a = gets.split(" ").each {|n| n.to_i}
puts "#{a[0] + a[1]}"
Say I input 1 2 into the above code. The output will be 12. How to do a simple addition with this code? For the output to be 3
Upvotes: 3
Views: 80
Reputation: 739
one-liner using Enumberable#map and Enumberable#reduce
gets.split.map(&:to_i).reduce(:+)
Upvotes: 0
Reputation: 110685
Suppose 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 since the dawn of time)
puts s.split.reduce(0) { |t,ss| t+ss.to_i }
42
Upvotes: 2
Reputation: 2183
Though accepted answer is correct but only for array with two elements(even for array with 1 element it will break). What if array size is variable? Ruby has more generic ways to do it.
You can use either reduce
or inject
method
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 output 28
Like reduce
you can use
a = gets.split(" ").map! {|n| n.to_i}
puts a.inject(:+)
Hope it will help someone.
Upvotes: 1
Reputation: 8888
each
won't change the array. You should use map!
a = gets.split(" ").map! {|n| n.to_i}
puts "#{a[0] + a[1]}"
Upvotes: 2