需要使它更像Ruby

时间:2014-04-18 05:36:17

标签: ruby

我是Ruby的新手,我似乎很乐意使用while循环。但我希望通过使用'每个'来简化我的代码。方法。我如何为这个特定的代码块做这个?

sum_array = []
i = 0
while i < array.length - 1
    j = i + 1
    while j < array.length
        sum = array[i] + array[j]
        if sum != 0
            sum_array << sum
        end 
        j += 1
    end
    i += 1
end

4 个答案:

答案 0 :(得分:4)

sum_array = array.combination(2).map{|n, m| n + m}.reject(&:zero?)

答案 1 :(得分:2)

array = (1..10).to_a # test array [1,2,3,4,....10]
sum_array = []
(0...array.length).each do |i| # from 0 to array.length-1
  (i+1...array.length).each do |j| # from i+1 to array.length-1
    sum = array[i] + array[j]
    sum_array << sum unless sum == 0 # brief condition
  end
end

答案 2 :(得分:0)

def sum_array(input)
  [].tap do |sums|
    input.each_with_index do |x, index|
      tail = input[index.next..-1]
      tail.each do |y| 
        sum = x + y
        sums << sum unless sum.zero?
      end
    end
  end
end

puts sum_array([1,2,0,0])
# => [3,1,1,2,2]

答案 3 :(得分:0)

你可以这样做:

sum_array = []
array.each_index do |i| 
  sum_array += (i+1...array.length).collect { |j| array[i] + array[j] }
end
sum_array.reject!(&:zero?)