使用重复提取两个字符

时间:2015-04-16 15:36:31

标签: ruby split character

我想分割这样的字符

输入: 12345678

我想要的输出: => [1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8]

怎么办?

1 个答案:

答案 0 :(得分:4)

Enumerable#each_cons可能会有所帮助:

str = "12345678"
out = str.chars.each_cons(2).to_a
#=> [["1", "2"], ["2", "3"], ["3", "4"], ["4", "5"], ["5", "6"], ["6", "7"], ["7", "8"]]
out2 = str.chars.map(&:to_i).each_cons(2).to_a
#=> [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8]]