开发者

Generate random string, without SecureRandom

I need to generate boundary for a multi-part upload

  post << "--#{BOUNDARY}\r\n"
  post << "Content-Disposition: form-开发者_如何学编程data; name=\"datafile\"; filename=\"#{filename}\"\r\n"
  post << "Content-Type: text/plain\r\n"
  post << "\r\n"
  post << file
  post << "\r\n--#{BOUNDARY}--\r\n"

The BOUNDARY need to be a random string (not present in the file).

In rails, I could do SecureRandom.hex(10)

Who can I do it without loading activesupport?


If you need a random alphanumeric string, use something like:

rand(10000000000000).floor.to_s(36)

This will make a random number (change the multiplier to make the string longer) and represent it in radix 36 (10 numbers + 26 letters).

For a Base64 string, you could do something like

require 'base64'
Base64.encode64(rand(10000000000000).to_s).chomp("=\n")

If you need strings of a fixed length, play with the random number range you're supplying, using something like 1000000 + rand(10000000).


Last time I used MD5 on rand like this:

require 'md5'
random_string = MD5.md5(rand(1234567).to_s).to_s


if you want random alphanumeric string then, you can do like below

 o =  [('a'..'z'),('A'..'Z'),('0'..'9')].map{|i| i.to_a}.flatten
 string  =  (0...50).map{ o[rand(o.length)]  }.join

This will also generate a alphanumeric random string

rand(36**length).to_s(36)

You can also pass the "length" to generate the size of random string. Ex.8 or 10

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜