ต้องการเปรียบเทียบ 2 arrays element-by-element หาความต่าง หาค่าสูงสุดแต่ละ index หรือ merge keys+values เป็น hash "Hard way" ใช้ map.with_index ยุ่งยาก
a = [1,2,3,4,5]; b = [1,2,3,6,8]
c = a.map.with_index { |_, idx| [a[idx], b[idx]] }
# [[1,1],[2,2],[3,3],[4,6],[5,8]]
Array#zip Way
a.zip(b) # [[1,1],[2,2],[3,3],[4,6],[5,8]]
เข้าใจง่าย Chain กับ Enumerable methods ได้:
a.zip(b).count { |a,b| a == b } # 3 (นับตำแหน่งที่เท่ากัน)
Merge Keys + Values → Hash
keys = %w(bacon coconut walnuts)
values = [100, 200, 300]
keys.zip(values).to_h # {"bacon"=>100, "coconut"=>200, "walnuts"=>300}
Caesar Cipher Example
letters = Array('a'..'z')
shift = 3
translation_map = letters.zip(letters.rotate(shift)).to_h
"hello".chars.map { |ch| translation_map[ch] }.join
Summary
Array#zip merge 2 arrays element-wise ทำ tricks ได้มาก: compare, count matches, build hash, cipher algorithms