Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting string into pair of characters in Ruby

Tags:

I have a string (e.g. "AABBCCDDEEFF") and want to split this into an array with each element containing two characters - ["AA", "BB", "CC", "DD", "EE", "FF"].

like image 451
LK. Avatar asked Feb 19 '09 09:02

LK.


People also ask

How do you split a string in Ruby?

Ruby – String split() Method with Examplessplit is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified. Here the pattern can be a Regular Expression or a string.

How do you split a string into characters?

(which means "any character" in regex), use either backslash \ to escape the individual special character like so split("\\.") , or use character class [] to represent literal character(s) like so split("[.]") , or use Pattern#quote() to escape the entire string like so split(Pattern.


1 Answers

Try the String object's scan method:

>> foo = "AABBCCDDEEFF" => "AABBCCDDEEFF" >> foo.scan(/../) => ["AA", "BB", "CC", "DD", "EE", "FF"] 
like image 138
Chris Bunch Avatar answered Dec 25 '22 12:12

Chris Bunch