user3451078
user3451078

Reputation: 33

Ruby - cannot convert individual chars in string to ASCII

I am trying to run the following code on http://repl.it/languages/Ruby/, but I am encountering a NoMethodError:

a = "string"
a.each_char do |c|
    puts c.ord
end

The error details are as follows:

(eval):1: undefined method `ord' for "s":String (NoMethodError)
    from (eval):0:in `each_char'
    from (eval):0

Please could somebody explain to me why my code does not work?

Upvotes: 0

Views: 162

Answers (2)

Phil Ross
Phil Ross

Reputation: 26100

The each_char method of String yields each character as a separate String.

The Ruby version running on repl.it is quite old (1.8.7). The String class in that version of Ruby doesn't define an ord method, so your code fails to run with a NoMethodError.

ord was added to String in Ruby 1.9, so your code will run on newer versions of Ruby.

On Ruby 1.8.7 (and repl.it), you could use one of the following alternatives instead:

a = "string"
a.each_char do |c|
    puts c[0]
end

a = "string"
a.each_byte do |c|
    puts c
end

However, please note that these examples won't behave identically to your original code if your string uses a multi-byte encoding. The ord method returns a Unicode code point. The Ruby 1.8.7 examples will give you individual bytes.

Upvotes: 1

Levsero
Levsero

Reputation: 641

The code as is will print the ascii code of each letter. Perhaps you're looking at the return value which would be the original string "string"?

Upvotes: 0

Related Questions