Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Ruby) Why does this work?

Tags:

ruby

I recently started learning ruby and am building a simple 'encryption' method. I'm getting the desired result, but I'm 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 am getting the desired encoded output: "Ymnx nx f yjxy", but I don't know why. I was expecting a string of numbers since I never specified that the letters be turned back into letters. Could someone please explain what is happening?

like image 664
mwstreit Avatar asked Sep 04 '26 22:09

mwstreit


1 Answers

Doc for String#<<

Append---Concatenates the given object to str. If the object is an Integer, it is considered as a codepoint, and is converted to a character before concatenation. Concat can take multiple arguments. All the arguments are concatenated in order.

The chars in the original String is converted to the ordinal integer, added with the offset and then fed to the String#<< method.

like image 198
Arie Xiao Avatar answered Sep 06 '26 23:09

Arie Xiao