Skip to content

Instantly share code, notes, and snippets.

@sharnie
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sharnie/d6fb0e327a94176aa7aa to your computer and use it in GitHub Desktop.
Save sharnie/d6fb0e327a94176aa7aa to your computer and use it in GitHub Desktop.
Ruby encode and decode method
# 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