Converting ruby array to array of consecutive pairs

后端 未结 2 1002
清酒与你
清酒与你 2020-12-03 09:42

What is the easiest way to convert a ruby array to an array of consecutive pairs of its elements?

I mean:

x = [:a, :b, :c, :d]

Expe

相关标签:
2条回答
  • 2020-12-03 10:15

    Use Enumerable#each_slice:

    y = x.each_slice(2).to_a
    #=> [[:a, :b], [:c, :d]]
    
    [0, 1, 2, 3, 4, 5].each_slice(2).to_a
    #=> [[0, 1], [2, 3], [4, 5]]
    
    0 讨论(0)
  • 2020-12-03 10:29
    Hash[*[:a, :b, :c, :d]].to_a
    
    0 讨论(0)
提交回复
热议问题