我試圖在引用塊中的索引時對數組的某些元素進行操作。操作整個陣列上很容易在不改變索引的情況下操作數組元素
arr = [1, 2, 3, 4, 5, 6, 7, 8]
arr.each_with_index { |num, index| puts "#{num}, "#{index}" }
但是如果我想與元素4
,只是工作6
返回
4, 3
6, 5
我可以創建原始的某些元素組成的新數組和運行該塊,但索引更改。
如何選擇元素及其索引?
我試圖在引用塊中的索引時對數組的某些元素進行操作。操作整個陣列上很容易在不改變索引的情況下操作數組元素
arr = [1, 2, 3, 4, 5, 6, 7, 8]
arr.each_with_index { |num, index| puts "#{num}, "#{index}" }
但是如果我想與元素4
,只是工作6
返回
4, 3
6, 5
我可以創建原始的某些元素組成的新數組和運行該塊,但索引更改。
如何選擇元素及其索引?
只要把一個條件就可以了:
indice = [3, 5]
arr.each_with_index do
|num, index| puts "#{num}, #{index}" if indice.include?(index)
end
這是另一種風格:
indice = [3, 5]
arr.each_with_index do
|num, index|
next unless indice.include?(index)
puts "#{num}, #{index}"
end
這工作!謝謝。 – sarkon 2015-02-06 20:36:41
我不能從問題告訴你是否給定的值在數組中,並希望獲得其索引, 或相反亦然。因此,我會爲每項任務提供一種方法。我會用這個數組的例子:
arr = [1, 2, 3, 4, 5, 6, 7, 8]
值以指數
如果您在給定的值:
vals = [4, 6]
可以檢索像這樣數量指數對:
可直接打印:vals.each { |num| puts "#{num}, #{arr.index(num)}" }
# 4, 3
# 6, 5
#=> [4, 6]
如果vals
中的元素不是在目前的arr
:
vals = [4, 99]
vals.map { |num| [num, arr.index(num)] }
#=> [[4, 3], [99, nil]]
指數以價值
如果你給出指標:
indices = [3, 5]
可以檢索索引值對像t他的:
indices.zip(arr.values_at(*indices))
#=> [[3, 4], [5, 6]]
然後以您喜歡的任何格式打印。
如果索引超出範圍,nil
將返回:
indices.zip(arr.values_at(*[3, 99]))
#=> [[3, 4], [5, nil]]
你的代碼是無效的。 – sawa 2015-02-06 20:31:01