Converting Characters into ASCII using Ruby

Ruby has special class String method called .ord that helps you to convert a specific character into ASCII code. For exmaples: “a”.ord will produce ASCII code of 97. Ruby allows you to convert ASCII code back into character by applying .chr method of String class in the following manner 97.char which will give you character “a” back.

Ruby string can act as an array and it allows you to access individual character within a string and convert it into ASCII string via my-string.each_byte method of the String class.

You can use each_byte method to convert string into ASCII code as specified in the following example.

'foo'.each_byte { |c| puts "#{c} = #{c.chr}" }
# 102 = f
# 111 = o
# 111 = o

This is useful for processing ASCII file for example.

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…