2017-07-06 48 views
-2

如何將此代碼轉換爲涉及顛倒數組迭代而不是索引的Ruby?Ruby反向迭代數組但不索引

out = 0 
    for index,x in enumerate(reversed(d)): 
     out += x*pow(2,index) 

從我可以從Python代碼瞭解,該陣列d得到逆轉,但該元素的索引都沒有?
加捻!
如何在Ruby中做到這一點?

+0

*「數組d是相反的,但元素的索引不是」* - 什麼? – jonrsharpe

+0

是啊!在這裏檢查代碼 - http://galvanist.com/post/53478841501/python-reverse-enumerate – arjun

回答

0

考慮在Python下一個輸出:

for index, string in enumerate(reversed(['zero', 'one', 'two'])): 
    print index, string 
# 0 two 
# 1 one 
# 2 zero 

然後你可以使用reverse應用枚舉,在這種情況下each之前,因此,它要你的陣列爲['two', 'one', 'zero'],索引每次迭代將保持不變:

['zero', 'one', 'two'].reverse.each_with_index do |word, index| 
    puts "#{index} #{word}" 
end 
# 0 two 
# 1 one 
# 2 zero 
+1

它會稍微更高性能(我認爲?...沒有基準測試)使用'[...] .reverse_each.with_index'。 –

+0

學會了一個新的竅門。現在看起來很容易!謝謝。 – arjun

+0

'reverse_each' [似乎](https://gist.github.com/vnhnhm/d84272d49b2462db862f4efeea809ae7)稍微慢一些。 –

2

用Ruby Python代碼段相對應的是:

d.reverse_each.with_index.inject(0) do |out, (x,i)| 
    out += x * 2**i 
end