If I had a string like the one below how would I split it at every 3rd character or any other specified character?
b = "123456789"
The result would be this:
b = ["123","456","789"]
I've tried using these method: b.split("").each_slice(3).to_a
But it results in this : [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"]]
Thank you for your help!
I'd use:
b = "123456789"
b.scan(/.{3}/) # => ["123", "456", "789"]
If the OP's sample were to be a different length, or it had an embedded "\n", a simple modification works:
b = "123456789"
b.scan(/.{1,3}/) # => ["123", "456", "789"]
b[0..-2].scan(/.{1,3}/) # => ["123", "456", "78"]
"#{ b }\n#{ b }".scan(/.{1,3}/) # => ["123", "456", "789", "123", "456", "789"]
Now, if there is an embedded "\n" NOT on an even "3" boundary, it breaks:
"#{ b[0..-2] }\n#{ b }".scan(/.{1,3}/) # => ["123", "456", "78", "123", "456", "789"]
but that is getting rather far afield from the OP's simple specification, and can be fixed by stripping the new-line(s) first:
"#{ b[0..-2] }\n#{ b }".delete("\n").scan(/.{1,3}/) # => ["123", "456", "781", "234", "567", "89"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With