Ruby将字符串拆分为每个字符的7个字符块

时间:2016-07-14 16:33:26

标签: ruby string split character

如何在ruby中执行以下操作:

a = 1234567890

Split into strings 7 characters in length at each character:

=> [1234567,2345678,3456789,4567890]

谢谢!

编辑:谢谢大家的帮助。很抱歉没有说出我的尝试(虽然没有什么能接近解决方案)。

4 个答案:

答案 0 :(得分:2)

a.to_s.each_char.each_cons(7).map{|s| s.join.to_i}
# => [1234567, 2345678, 3456789, 4567890]

答案 1 :(得分:1)

a = 1234567890

# Convert to a string, then convert that string
# into an array of characters
chars = a.to_s.chars # => ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]

slices = []

# Slice the array into groups of 7, with successive indices
chars.each_cons(7) do |cons|
  slices << cons.join # Join each 7-item array into a string and push it
end

p slices # => ["1234567", "2345678", "3456789", "4567890"]

您正在寻找的关键方法是each_cons

答案 2 :(得分:0)

如果您喜欢使用一些更加模糊的Ruby方法,那么这也适用:

(0..a.to_s.size-7).map { |i| a.to_s.chars.rotate(i).take(7).join.to_i }
#=> [1234567, 2345678, 3456789, 4567890]

答案 3 :(得分:0)

a.to_s.scan(/(?=(.{7}))/).map { |arr| arr.first.to_i }
  #=> [1234567, 2345678, 3456789, 4567890] 

(?= ... )是一个积极的前瞻。 (.{7})匹配捕获组1中的后七个字符。有关scan如何处理捕获组,请参阅String#scan。我们有

s = a.to_s
  #=> "1234567890" 
b = s.scan(/(?=(.{7}))/)
  #=> [["1234567"], ["2345678"], ["3456789"], ["4567890"]] 
b.map { |arr| arr.first.to_i }
  #=> [1234567, 2345678, 3456789, 4567890]