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.