정수 배열이 있습니다.
예를 들어
array = [123,321,12389]
이 둘의 합계를 구하는 좋은 방법이 있나요?
알아요, 그
sum = 0
array.each { |a| sum+=a }
가 효과가 있을 거라고요.
이렇게 해보세요:
array.inject(0){|sum,x| sum + x }
(참고: nil
대신 빈 배열에 0
이 반환되도록 0
대소문자가 필요합니다).
array.reduce(0, :+)
같은 기간 동안 라이스잉젝트 (0, :+) ',' 를 입력하면 절감하십시오 는 보다 일반적인 대중 작용하고 있는 MapReduce 프로그래밍 모델을.
강조하기 위해 매핑해야 줄일 수 있습니다. 문장, 여기 있는 이 버전에 따라 조금 더 관대하시며 motor1.1end 백업하도록 어레이입니다.
array.map(&:to_i).reduce(0, :+)
일부 추가 관련 판독값:
[2]: http://en.wikipedia.org/wiki/Reduce_% 28higher-order_function% 29
(1..100).sum
#=> 5050
[1, 2, 4, 9, 2, 3].sum
#=> 21
[1.9, 6.3, 20.3, 49.2].sum
#=> 77.7
이 방법을 사용할 수 없습니다 (:+) '와' # 했다. 예를 들어
%w(a b c).inject(:+)
#=> "abc"
%w(a b c).sum
#=> TypeError: String can't be coerced into Integer
또한
(1..1000000000).sum
#=> 500000000500000000 (execution time: less than 1s)
(1..1000000000).inject(:+)
#=> 500000000500000000 (execution time: upwards of a minute)
[이 오토메이티드] 참조 (https://stackoverflow.com/a/41449844/5021321) 이 같은 이유에 대한 자세한 정보는 '숨' 은 (는).
루비 2.4.0 는 릴리즈됨 또한 [ui_policytable_java_spe_policy 열거 # 합] [1] 메서드입니다. 할 수 있도록
array.sum
예) 의 문서:
{ 1 => 10, 2 => 20 }.sum {|k, v| k * v } #=> 50
(1..10).sum #=> 55
(1..10).sum {|v| v * 2 } #=> 110
[1]: # 내가 혹시 방법 .0/enumerable.html http://ruby-doc.org/core-2.4
# http://madeofcode.com/posts/74-ruby-core-extension-array-sum
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
[1] pry(main)> [1,2,3,4].sum
=> 10
[2] pry(main)> [].sum
=> 0
[3] pry(main)> [1,2,3,5,nil].sum
TypeError: nil can't be coerced into Integer
[24] pry(main)> [].inject(:+)
=> nil
[25] pry(main)> [].inject(0, :+)
=> 0
[4] pry(main)> [1,2,3,4,5].inject(0, :+)
=> 15
[5] pry(main)> [1,2,3,4,nil].inject(0, :+)
TypeError: nil can't be coerced into Integer
from (pry):5:in `+'
[6] pry(main)> [1,2,3].reduce(:+)
=> 6
[9] pry(main)> [].reduce(:+)
=> nil
[7] pry(main)> [1,2,nil].reduce(:+)
TypeError: nil can't be coerced into Integer
from (pry):7:in `+'
>. TypeError: # 39 로, t be 강압 can& 모두 정수
이를 극복할 수 있습니다,
[16] pry(main)> sum = 0
=> 0
[17] pry(main)> [1,2,3,4,nil, ''].each{|a| sum+= a.to_i }
=> [1, 2, 3, 4, nil, ""]
[18] pry(main)> sum
=> 10
루비 (s) 의 전체 표현식에서는 구체화하십시오.
[26] pry(main)> a = [1,3,4,5]
=> [1, 3, 4, 5]
[27] pry(main)> eval a.join '+'
=> 13
[30] pry(main)> a = [1,3,4,5, nil]
=> [1, 3, 4, 5, nil]
[31] pry(main)> eval a.join '+'
SyntaxError: (eval):1: syntax error, unexpected end-of-input
1+3+4+5+