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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With