Tony DiNitto
Tony DiNitto

Reputation: 1239

Converting a long string into evenly split indexes in an Array

I'm trying to convert the string: "Stack_Overflow" to an array that's split by a predetermined amount of characters (say 5 characters):

result = ["Stack", "_Over", "flow"]

If there's nothing that can do that cleanly, I can make a loop that can do it for me as long as I could do something even more basic such as have an array like:

["S", "t", "a", "c", "k"]

And turn it into:

["Stack"]

I know how to combine the array using the Array#join method, but this turns it into an string. And using the << operator will simply add an extra element, and I need to shovel into the SAME element. And Array#flatten won't work exactly like changing the index value itself either. Maybe if I could String#split the string to begin with, I could convert it then. But the split method wants to see a pattern/character to indicate a split, and it needs to simply be a number of characters. So I'm a bit at a loss from my research.

Upvotes: 1

Views: 160

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110725

I prefer @spickermann's use of a regex, but here's another way that uses two enumerators to avoid the creation of temporary arrays:

str = "It was the best of times, it was the worst of times."

str.each_char.each_slice(5).map(&:join)
  # => ["It wa", "s the", " best", " of t", "imes,", " it w",
  #     "as th", "e wor", "st of", " time", "s."] 

Upvotes: 4

spickermann
spickermann

Reputation: 107047

That can be done with String#scan:

"Stack_Overflow".scan(/.{1,5}/)
#=> ["Stack", "_Over", "flow"]

Chance the 5 to whatever predetermined amount of characters you want.

Upvotes: 6

Related Questions