(Ruby) Why does it work?

I recently started learning ruby ​​and am creating a simple encryption method. I am getting the desired result, but I am not sure why.

string = "This is a test"
offset = 5

def encode(string, offset)
    coded = ""
    string.scan(/./) do |char|
        numbers = char.ord
        if numbers == 32
            numbers = numbers
        else
            numbers = numbers + offset
        end
        coded << numbers
    end
    return coded
end

puts encode(string, offset)

      

I get the coded output I want: "Ymnx nx f yjxy", but I don't know why. I was expecting a string of numbers, since I never specified that letters would be returned in letters. Can someone please explain what's going on?

+3


source to share


1 answer


Doc for String#<<

Add --- Concatenate the given object to str. If the object is Integer, it is considered a code point and converted to a character before concatenation. Concat can take multiple arguments. All arguments are concatenated in order.



The fonts in the original string are converted to an ordinal integer, appended with an offset, and then passed to the method String#<<

.

+7


source







All Articles