gstnem
gstnem

Reputation: 39

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).

Upvotes: 0

Views: 870

Answers (4)

Sagar Pandya
Sagar Pandya

Reputation: 9498

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]

Upvotes: 0

Cary Swoveland
Cary Swoveland

Reputation: 110725

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] 

Upvotes: 0

Dylan L
Dylan L

Reputation: 89

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.

Upvotes: 1

sawa
sawa

Reputation: 168209

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

Upvotes: 2

Related Questions