Last active
August 29, 2015 14:00
-
-
Save sharnie/d6fb0e327a94176aa7aa to your computer and use it in GitHub Desktop.
Ruby encode and decode method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# created a method name 'encode' that accept an argument 'string' | |
# and then call the "pack('m')" method on the string | |
def encode string | |
[string].pack("m") | |
end | |
# assign encode value of 'I love food' to string_encode variable. | |
puts string_encode = encode("I love food") # the return value is 'SSBsb3ZlIGZvb2Q=' | |
# encoding strings is pretty cool, but how do you decode them? | |
# the method below decode strings perfectly. | |
# instead of pack, we use unpacked this time. This will give us the original string. | |
def decode string | |
string.unpack("m") | |
end | |
# output the return value of string_encode when we pass it to the decode method | |
puts decode(string_encode) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment