이 코드에 대한 기대치는 3입니다. 왜 작동하지 않습니까?혼합 배열로 숫자 추가
mixed_array=[1,'cat',2]
mixed_array.inject(0) do |memo,num|
memo += num if num.is_a?Integer
end
NoMethodError: undefined method `+' for nil:NilClass
이 코드에 대한 기대치는 3입니다. 왜 작동하지 않습니까?혼합 배열로 숫자 추가
mixed_array=[1,'cat',2]
mixed_array.inject(0) do |memo,num|
memo += num if num.is_a?Integer
end
NoMethodError: undefined method `+' for nil:NilClass
당신은 거의 있었다 :
mixed_array.inject(0) do |memo, num|
next memo unless num.is_a?(Integer)
memo + num
end
#=> 3
이 코드 작업을 만들기 :
mixed_array.inject(0) do |memo, num|
memo += num if num.is_a?(Integer)
memo # return memo on each iteration, because it becomes nil with non-integer element
end
#=> 3
당신은 작동하지 않습니다이 무엇 때문에 :
memo += num if num.is_a?Integer
의 값일 때 은 Integer
이 아닙니다.memo
으로 입력됩니다.귀하의 블록은 평가하려고 끝날거야, 그래서 두 번째 반복에 nil
로 평가
nil += 2 if 2.is_a? Integer
하고 NoMethodError이있다.
mixed_array.select { |e| e.is_a? Integer }.inject(:+)
또는 어쩌면 느슨한 버전 :
당신은 명확성을 위해 두 단계로이 일을 떨어져 아마 더 좋을 것 같아
mixed_array.select { |e| e.is_a? Numeric }.sum
:
mixed_array.select { |e| e.is_a? Numeric }.inject(:+)
또는 루비의 최신 버전과
독단적으로 삼자에 반대하지 않는다면 다음과 같이 말할 수도 있습니다.
mixed_array.inject(0) { |memo, num| memo + (num.is_a?(Integer) ? num : 0) }
mixed_array.sum { |e| e.is_a?(Integer) ? e : 0 }
당신은 mixed_array
의 숫자가 아닌 요소가 숫자 모양 또는 숫자로 시작하지 않는 문자열 (것을 알고있는 경우 즉,
mixed_array.map(&:to_i).inject(:+)
mixed_array.inject(0) { |memo, num| memo + num.to_i }
...
을하지만 그건 아마 너무 많은 가정을 만들고있다 : '0'
, '11 pancakes'
처럼 ... 아무것도) 당신은 말할 수 없었다.
당신은 훨씬 더 쉽게 당신이 하나가 아닌 2 단계 작업으로 고려하는 경우이 작업을 수행 할 수 있습니다이 배열의 모든 정수가 아닌 요소를 걸러 함께 나머지를 추가
mixed_array=[1,'cat',2]
mixed_array.grep(Integer).inject(0, :+)
# => 3
.
inject
은 이전 반복의 반환 값을 다음 반복의 시드로 취합니다. if
조항 은 대체 값을 반환해야합니다.당신이 그것을 해결하는 경우이와 끝까지 :
memo += num.is_a?(Integer) ? num : 0
또한 같은 좋은만큼 솔루션으로 갈 수있다 : 당신이 화면에 노력하고있는 데이터의 종류에 따라
memo += num.to_i
아웃.
mixed_array = [1, 'cat', 2, [3, 4], :a, { b: 5, c: 6 }, 7]
mixed_array.reduce(0) { |tot, obj| tot += Integer(obj) rescue 0 }
#=> 10
배열이 하나 이상의 수레를 포함 할 수있다 그리고 당신은 부동 반환 할 :
mixed_array = [1, 'cat', 2, [3, 4], :a, { b: 5, c: 6 }, 7, 8.123]
mixed_array.reduce(0) { |tot, obj| tot += Float(obj) rescue 0 }
#=> 18.122999999999998
이 Kernel::Integer 및 Kernel::Float 참조하십시오.