Created
March 8, 2018 12:59
-
-
Save prodoxx/391c2336d4c809b3a680737ab7522342 to your computer and use it in GitHub Desktop.
Packs a short string into a Fixnum and vise-versa
This file contains hidden or 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
class ShortStringPacker | |
## Packs a short string into a Fixnum | |
# Arguments: | |
# str - String object | |
# Returns: a Fixnum object | |
def self.pack(str) | |
abc = [*'a'..'z'] | |
arr = str.chars.map { |x| abc.find_index(x) + 1 } | |
arr.reduce { |item, key| (item << 5.0) | key } | |
end | |
## Unpacks a Fixnum from pack() method into a short string | |
# Arguments: | |
# packed - a Fixnum object | |
# Returns: a String object | |
def self.unpack(packed) | |
abc = [*'a'..'z'] | |
binary_string = packed.to_s 2 | |
amt_chars_in_packed = (binary_string.length / 5.0).ceil | |
binary_string.rjust(amt_chars_in_packed * 5.0, '0') | |
.to_s | |
.chars | |
.each_slice(5) | |
.map(&:join) | |
.map! { |x| abc[(x.to_i 2) - 1] } | |
.join | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment