繁体   English   中英

Ruby在每个字符处将字符串分成7个字符块

[英]Ruby split string into 7 character chunks at each character

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

a = 1234567890

Split into strings 7 characters in length at each character:

=> [1234567,2345678,3456789,4567890]

谢谢!

编辑:谢谢大家的所有帮助。 对不起,我没有说我尝试过的内容(尽管没有什么可以解决)。

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

如果您喜欢使用一些更晦涩的Ruby方法,那么它也可以工作:

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

(?= ... )是一个积极的前瞻。 (.{7})匹配捕获组下一七个字符1.见字符串#扫描如何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] 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM