Class: Xencoder::Encoder
- Inherits:
-
Object
- Object
- Xencoder::Encoder
- Defined in:
- lib/xencoder/encoder.rb
Instance Attribute Summary collapse
-
#chars ⇒ Object
readonly
Returns the value of attribute chars.
-
#length ⇒ Object
readonly
Returns the value of attribute length.
-
#max ⇒ Object
readonly
Returns the value of attribute max.
-
#seed ⇒ Object
readonly
Returns the value of attribute seed.
Instance Method Summary collapse
- #decode(str) ⇒ Object
- #encode(number) ⇒ Object
-
#initialize(chars, length: 6, seed: 1) ⇒ Encoder
constructor
A new instance of Encoder.
Constructor Details
#initialize(chars, length: 6, seed: 1) ⇒ Encoder
Returns a new instance of Encoder.
5 6 7 8 9 10 11 12 |
# File 'lib/xencoder/encoder.rb', line 5 def initialize(chars, length: 6, seed: 1) @chars = build_chars(chars).freeze @length = length @seed = seed @xbase = Xbase.new(@chars) @base = @xbase.to_i("#{chars[1]}#{chars[0] * (length - 1)}") @max = @xbase.to_i(chars[-1] * length) - @base end |
Instance Attribute Details
#chars ⇒ Object (readonly)
Returns the value of attribute chars.
3 4 5 |
# File 'lib/xencoder/encoder.rb', line 3 def chars @chars end |
#length ⇒ Object (readonly)
Returns the value of attribute length.
3 4 5 |
# File 'lib/xencoder/encoder.rb', line 3 def length @length end |
#max ⇒ Object (readonly)
Returns the value of attribute max.
3 4 5 |
# File 'lib/xencoder/encoder.rb', line 3 def max @max end |
#seed ⇒ Object (readonly)
Returns the value of attribute seed.
3 4 5 |
# File 'lib/xencoder/encoder.rb', line 3 def seed @seed end |
Instance Method Details
#decode(str) ⇒ Object
25 26 27 28 29 30 31 32 33 34 |
# File 'lib/xencoder/encoder.rb', line 25 def decode(str) str = str.dup 0.upto(str.length - 2).each do |i| idx = chars.index(str[i + 1]) idx2 = (chars.index(str[i]) - idx + chars.size) % chars.size str[i] = mappings.at(idx2) str[i + 1] = mappings.at(idx) end @xbase.to_i(str) - @base end |
#encode(number) ⇒ Object
14 15 16 17 18 19 20 21 22 23 |
# File 'lib/xencoder/encoder.rb', line 14 def encode(number) str = @xbase.to_x(number + @base) (str.length - 1).downto(1).each do |i| idx = mappings.index(str[i]) idx2 = (mappings.index(str[i - 1]) + idx) % mappings.size str[i] = chars.at(idx) str[i - 1] = chars.at(idx2) end str end |