Home > Articles > Programming > Ruby

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

2.15 Converting Between Characters and ASCII Codes

Single characters in Ruby are returned as one-character strings. Here is an example:

str = "Martin"
print str[0]        # "M"

The Integer class has a method called chr that will convert an integer to a character. By default, integers will be interpreted as ASCII, but other encodings may be specified for values greater than 127. The String class has an ord method that is in effect an inverse:

str = 77.chr            # "M"
s2  = 233.chr("UTF-8")  # "é"
num = "M".ord           # 77
  • + Share This
  • 🔖 Save To Your Account