Sunday, April 3, 2011

Splitting string into pair of characters in Ruby

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"].

From stackoverflow
  • Try the String object's scan method:

    >> foo = "AABBCCDDEEFF"
    => "AABBCCDDEEFF"
    >> foo.scan(/../)
    => ["AA", "BB", "CC", "DD", "EE", "FF"]
    
  • Depending on your needs, this may work better:

    >  foo = "AAABBCDEEFF"
    => "AAABBCDEEFF"
    > foo.scan(/.{1,2}/)
    => ["AA", "AB", "BC", "DE", "EF", "F"]
    

    Not sure what your input looks like. The above answer will drop any characters that do not have a pair, this one will work on odd length strings.

0 comments:

Post a Comment