如何将字符串切成对

时间:2015-01-16 19:33:12

标签: ruby arrays split

对于我正在进行的项目,我需要在输入中进行配对,但我无法弄清楚如何,我可以使用一些帮助。
它是怎么回事:

2209222717080109

我希望它成为:

["22","09","22","27","17","08","01","09"]

3 个答案:

答案 0 :(得分:4)

"2209222717080109".scan /../
  #=> ["22", "09", "22", "27", "17", "08", "01", "09"] 

答案 1 :(得分:3)

input = "2209222717080109"
input.chars.each_slice(2).map(&:join)
["22", "09", "22", "27", "17", "08", "01", "09"]

答案 2 :(得分:2)

Convert it to a stringconvert that into an array of characters,然后获取两个字符each consecutive slicejoin each of those slices一起:

2209222717080109.to_s.chars.each_slice(2).map(&:join)
#=> ["22", "09", "22", "27", "17", "08", "01", "09"]