试图从数组中求和
Trying to sum from array
a = gets.split(" ").each {|n| n.to_i}
puts "#{a[0] + a[1]}"
假设我在上面的代码中输入了 1 2 。
输出将是 12。
如何用这段代码做一个简单的加法?输出为 3
each
不会更改数组。你应该使用 map!
a = gets.split(" ").map! {|n| n.to_i}
puts "#{a[0] + a[1]}"
尽管接受的答案是正确的,但仅适用于 具有两个元素的数组(即使对于具有 1 个元素的数组也会中断)。如果数组大小可变怎么办? Ruby 有更通用的方法来做到这一点。
您可以使用 reduce
或 inject
方法
documentation
示例代码:
a = gets.split(" ").map! {|n| n.to_i}
puts a.reduce(:+)
如果我输入1 2 3 4 5 6 7
那么它会输出28
喜欢reduce
可以使用
a = gets.split(" ").map! {|n| n.to_i}
puts a.inject(:+)
希望对大家有所帮助。
假设gets
returns
s = "21 14 7"
然后使用Array#sum(Ruby v.2.4.0 中的新功能):
puts s.split.sum(&:to_i)
42
或使用 Enumerable#reduce(又名 inject
,自古以来可用)
puts s.split.reduce(0) { |t,ss| t+ss.to_i }
42
单线使用Enumberable#map and Enumberable#reduce
gets.split.map(&:to_i).reduce(:+)
a = gets.split(" ").each {|n| n.to_i}
puts "#{a[0] + a[1]}"
假设我在上面的代码中输入了 1 2 。 输出将是 12。 如何用这段代码做一个简单的加法?输出为 3
each
不会更改数组。你应该使用 map!
a = gets.split(" ").map! {|n| n.to_i}
puts "#{a[0] + a[1]}"
尽管接受的答案是正确的,但仅适用于 具有两个元素的数组(即使对于具有 1 个元素的数组也会中断)。如果数组大小可变怎么办? Ruby 有更通用的方法来做到这一点。
您可以使用 reduce
或 inject
方法
documentation
示例代码:
a = gets.split(" ").map! {|n| n.to_i}
puts a.reduce(:+)
如果我输入1 2 3 4 5 6 7
那么它会输出28
喜欢reduce
可以使用
a = gets.split(" ").map! {|n| n.to_i}
puts a.inject(:+)
希望对大家有所帮助。
假设gets
returns
s = "21 14 7"
然后使用Array#sum(Ruby v.2.4.0 中的新功能):
puts s.split.sum(&:to_i)
42
或使用 Enumerable#reduce(又名 inject
,自古以来可用)
puts s.split.reduce(0) { |t,ss| t+ss.to_i }
42
单线使用Enumberable#map and Enumberable#reduce
gets.split.map(&:to_i).reduce(:+)