Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

2.6 Processing a Character or Byte at a Time

Ruby used to treat each byte as a character, but that is no longer the case. The bytes in a string are available as an array via the bytes method. To process the bytes, one at a time, use the each_byte iterator:

str = "ABC"
str.each_byte {|byte| print byte, " " }
puts
# Produces output: 65 66 67

A character is essentially the same as a one-character string. In multibyte encodings, a one-character string may be more than one byte:

str = "ABC"
str.each_char {|char| print char, " " }
puts
# Produces output: A B C

In any version of Ruby, you can break a string into an array of one-character strings by using scan with a simple wildcard regular expression matching a single character:

str = "ABC"
chars = str.scan(/./)
chars.each {|char| print char, " " }
puts
# Produces output: A B C
  • + Share This
  • 🔖 Save To Your Account