2011-10-10 72 views

回答

6

像這樣:

range = 1..5 
store = 0 

range.each_with_index do |value, i| 
    next_value = range.to_a[i+1].nil? ? 0 : range.to_a[i+1] 
    store += value + next_value 
end  

p store # => 29 

可能有更好的方法,但這個工程。

你可以得到下一個這樣的下一個值:

,不會使用索引
range.to_a[i+2] 
+1

如果範圍發生了變化,這段代碼就會中斷,比如「11..15」:當它給出119時,它會給出65. –

+0

很好!感謝您的快速回復!再次想到@AndrewGrimm是對的。 – jovhenni19

+0

@AndrewGrimm,你說得對,讓我解決它。 – Mischa

1

一種方法是可枚舉#郵編:

range = 11..15 
store = 0 # This is horrible imperative programming 
range.zip(range.to_a[1..-1], range.to_a[2..-1]) do |x, y, z| 
    # nil.to_i equals 0 
    store += [x, y, z].map(&:to_i).inject(:+) 
end 
store 
10

從早Ruby 1.8.7時,枚舉模塊有一個方法each_cons,它幾乎完全符合您的要求:

個each_cons(N){...}→零個
each_cons(N)→an_enumerator

迭代連續<Ñ>元件的每個陣列的給定的塊。如果沒有給出塊,則返回一個枚舉器。

例如爲:

(1..10).each_cons(3) { |a| p a } 
# outputs below 
[1, 2, 3] 
[2, 3, 4] 
[3, 4, 5] 
[4, 5, 6] 
[5, 6, 7] 
[6, 7, 8] 
[7, 8, 9] 
[8, 9, 10] 

唯一的問題是,它不重複的最後一個元素。但這是微不足道的解決。具體而言,您希望

store = 0 
range = 1..5 

range.each_cons(2) do |i, next_value_of_i| 
    store += i + next_value_of_i 
end 
store += range.end 

p store # => 29 

但你也可以這樣做:

range = 1..5 

result = range.each_cons(2).reduce(:+).reduce(:+) + range.end 

p result # => 29 

或者,你可能會發現以下更可讀:

result = range.end + range.each_cons(2) 
          .reduce(:+) 
          .reduce(:+) 
相關問題