简体   繁体   中英

Ruby split string into 7 character chunks at each character

How can I do the following in ruby:

a = 1234567890

Split into strings 7 characters in length at each character:

=> [1234567,2345678,3456789,4567890]

Thanks!

Edit: Thank you everyone for all the help. Sorry for not saying what I had attempted (although nothing was close to a solution).

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"]

The key method you're looking for is each_cons .

If you fancy using some more obscure Ruby methods then this works too:

(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] 

(?= ... ) is a positive lookahead. (.{7}) matches the next seven characters in capture group 1. See String#scan for how scan treats capture groups. We have

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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