Ruby에서 숫자 배열을 합하는 방법은 무엇입니까?
정수 배열이 있습니다.
예를 들면 :
array = [123,321,12389]
합계를 얻는 좋은 방법이 있습니까?
알아요
sum = 0
array.each { |a| sum+=a }
작동 할 것이다.
이 시도:
array.inject(0){|sum,x| sum + x }
(참고 : 대신 빈 배열에 반환 0되도록 기본 케이스가 필요합니다. )0nil
또는 Ruby 1.9 방식을 사용해보십시오.
array.inject(0, :+)
참고 : 0기본 케이스가 필요합니다. 그렇지 않으면 nil빈 배열에 반환됩니다.
> [].inject(:+)
nil
> [].inject(0, :+)
0
array.reduce(0, :+)
와 동일하지만 array.inject(0, :+), 감소 라는 용어 는 MapReduce 프로그래밍 모델 의 부상과 함께보다 일반적인 언어로 접어 들고 있습니다 .
inject , reduce , fold , accumulate , compress 는 모두 접기 함수 의 클래스와 동의어 입니다. 코드 기반 전체에서 일관성이 가장 중요하다고 생각하지만 다양한 커뮤니티가 한 단어를 다른 단어보다 선호하는 경향이 있기 때문에 대안을 아는 것이 유용합니다.
지도 축소 표현을 강조하기 위해 여기에 해당 배열에서 끝나는 것에 대해 좀 더 관용적 인 버전이 있습니다.
array.map(&:to_i).reduce(0, :+)
몇 가지 추가 관련 자료 :
- http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-inject
- http://en.wikipedia.org/wiki/MapReduce
- http://en.wikipedia.org/wiki/Fold_(higher-order_function)
또는 (비교를 위해) Rails가 설치된 경우 (실제로는 ActiveSupport 만 해당) :
require 'activesupport'
array.sum
Ruby> = 2.4.0의 경우 sumEnumerables에서 사용할 수 있습니다 .
[1, 2, 3, 4].sum
기본 클래스를 mokeypatch하는 것은 위험합니다. 위험을 좋아하고 이전 버전의 Ruby를 사용하는 #sum경우 Array클래스에 추가 할 수 있습니다 .
class Array
def sum
inject(0) { |sum, x| sum + x }
end
end
Ruby 2.4.0의 새로운 기능
적절하게 명명 된 메서드를 사용할 수 있습니다 Enumerable#sum. 많은 장점이 inject(:+)있지만 마지막에 읽어야 할 중요한 메모도 있습니다.
예
범위
(1..100).sum
#=> 5050
배열
[1, 2, 4, 9, 2, 3].sum
#=> 21
[1.9, 6.3, 20.3, 49.2].sum
#=> 77.7
중요 사항
이 메서드는 #inject(:+). 예를 들면
%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)
왜 이와 같은지에 대한 자세한 내용 은 이 답변 을 참조하십시오 sum.
다양성을 위해 배열이 숫자 배열이 아니라 숫자 (예 : 양) 인 속성을 가진 객체 배열 인 경우에도 이렇게 할 수 있습니다.
array.inject(0){|sum,x| sum + x.amount}
Ruby 2.4+ / Rails- array.sumie[1, 2, 3].sum # => 6
Ruby pre 2.4 - array.inject(:+) or array.reduce(:+)
*Note: The #sum method is a new addition to 2.4 for enumerable so you will now be able to use array.sum in pure ruby, not just Rails.
ruby 1.8.7 way is the following:
array.inject(0, &:+)
You can simply use:
example = [1,2,3]
example.inject(:+)
This is Enough [1,2,3].inject('+')
Ruby 2.4.0 is released, and it has an Enumerable#sum method. So you can do
array.sum
Examples from the docs:
{ 1 => 10, 2 => 20 }.sum {|k, v| k * v } #=> 50
(1..10).sum #=> 55
(1..10).sum {|v| v * 2 } #=> 110
Also allows for [1,2].sum{|x| x * 2 } == 6:
# 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
for array with nil values we can do compact and then inject the sum ex-
a = [1,2,3,4,5,12,23.45,nil,23,nil]
puts a.compact.inject(:+)
array.reduce(:+)
Works for Ranges too... hence,
(1..10).reduce(:+) returns 55
If you feel golfy, you can do
eval([123,321,12389]*?+)
This will create a string "123+321+12389" and then use function eval to do the sum. This is only for golfing purpose, you should not use it in proper code.
Method 1:
[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
Method 2:
[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 `+'
Method 3:
[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 `+'
Method 4: When Array contains an nil and empty values, by default if you use any above functions reduce, sum, inject everything will through the
TypeError: nil can't be coerced into Integer
You can overcome this by,
[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
Method 6: eval
Evaluates the Ruby expression(s) in string.
[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+
Or you can try this method:
def sum arr
0 if arr.empty
arr.inject :+
end
This is the shortest way. Try it.
array.inject :+
number = [1..100]
number. each do |n|
final_number = n.sum
puts "The sum is #{final_number}"
end
*This worked well for me as a new developer. You can adjust your number range by changing the values within the []
You can also do it in easy way
def sum(numbers)
return 0 if numbers.length < 1
result = 0
numbers.each { |num| result += num }
result
end
You can use .map and .sum like:
array.map { |e| e }.sum
참고URL : https://stackoverflow.com/questions/1538789/how-to-sum-array-of-numbers-in-ruby
'Programing' 카테고리의 다른 글
| Xcode 편집기에서 줄 번호는 어디에서 찾을 수 있습니까? (0) | 2020.10.04 |
|---|---|
| 전체 ASCII 파일을 C ++ std :: string [duplicate]로 읽기 (0) | 2020.10.04 |
| Pytz 시간대 목록이 있습니까? (0) | 2020.10.04 |
| 크로스 스레드 작업이 유효하지 않음 : 생성 된 스레드가 아닌 스레드에서 액세스 된 제어 (0) | 2020.10.04 |
| 함수를 C에서 매개 변수로 어떻게 전달합니까? (0) | 2020.10.04 |