2016-07-01 33 views

回答

2

使用String#each_char

"abcdef".each_char.each_cons(3) { |a| p a } 
["a", "b", "c"] 
["b", "c", "d"] 
["c", "d", "e"] 
["d", "e", "f"] 
=> nil 
0

补充对方的回答。

"abcdef".each_char.to_a.in_groups_of(3) 
+0

1.'in_groups_of'是一个Rails方法。 2.结果不同。 – Ilya

+0

谢谢,我没有想到这一点。 – fabriciofreitag

1

如果你想长的3 “连续串”:

r =/
    (?=  # begin a positive lookahead 
     ((.{3}) # match any three characters in capture group 1 
    )   # close the positive lookahead 
    /x  # free-spacing regex definition mode 

"abcdef".scan(r).flatten 
    #=> ["abc", "bcd", "cde", "def"] 

写在传统的方式,这正则表达式是:

r = /(?=(.{3}))/ 

如果你想的数组的数组三个字母,这样做:

"abcdef".scan(/(?=(.{3}))/).flatten.map { |s| s.split('') } 
    #=> [["a", "b", "c"], ["b", "c", "d"], ["c", "d", "e"], ["d", "e", "f"]]