Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you slice or split a string on a certain character in Ruby?

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!

like image 976
Jamaal Avatar asked Nov 28 '22 07:11

Jamaal


1 Answers

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"]
like image 135
the Tin Man Avatar answered Dec 23 '22 08:12

the Tin Man