no implicit conversion of String into Integer base62 encode rails

741 views Asked by At
uuid = Digest::SHA256.digest(SecureRandom.uuid)
id = Base62.encode(uuid)

no implicit conversion of String into Integer

line = id = Base62.encode(uuid)

2

There are 2 answers

0
andrea paola vecino pastrana On BEST ANSWER

for pass string to base62

uuid = SecureRandom.uuid.gsub("-", "").hex
@id = uuid.base62_encode
1
James Milani On

I don't think that your code is going to work. Here's why:

Base62.encode(num) takes a base10 number and converts it into a base62 string. That's a problem for you as:

Digest::SHA256.digest(SecureRandom.uuid)
# => "\e\x1F\xD6yby\x02o\f)\xA2\x91\xD4\xFB\x85jd\xE0\xF7\xECtd\x8E\xA6\x9Ez\x99\xD8>\x04\nT"

Returns a string.

If you look at the code in the base62-rb gem, and the comment above the method, you can see it's comparing a string to an integer, which is the error I get when I try to replicate this:

ArgumentError: comparison of String with 0 failed

Here's is the method from the gem:

# From base62-rb.rb line 8-20:

  # Encodes base10 (decimal) number to base62 string.
  def self.encode(num)
    return "0" if num == 0
    return nil if num < 0

    str = ""
    while num > 0
      # prepend base62 charaters
      str = KEYS[num % BASE] + str
      num = num / BASE
    end
    str
  end

All of this is of course predicated on the fact that you are using the base62-rb gem. So, perhaps you can give us some context and let us know what you've tried?