Ruby Tuesday – String#codepoints

Today’s Ruby Tuesday is on String#codepoints.

String#codepoints returns an Array of Integers that represent the values of the characters in the string.

"Hello, World!".codepoints
# => [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33]
"rn".codepoints
# => [13, 10]

For ASCII characters this is what we would expect when looking at an ASCII chart of characters to the decimal value that represents them, but it also works on extended character sets such as Unicode.

"こんにちは世界".codepoints
# => [12371, 12435, 12395, 12385, 12399, 19990, 30028]
"💾".codepoints
# => [128190]

As String#codepoints returns an Array, we can also use the standard methods from the Enumerable module to modify a String.

"HAL".codepoints.map{|codepoint| codepoint + 1}.reduce("", &:<<)
# => "IBM"

And it even works on Unicode characters as well.

"💾".codepoints.map{|codepoint| codepoint + 1}.reduce("", &:<<)
# => "💿"

–Proctor