ruby - To obtain random pair from Hash -


part of class keyserver

@generated_keys = hash.new  def generate_key     key = securerandom.urlsafe_base64     while(purged_keys.include?(key))       key = securerandom.urlsafe_base64     end     #add new key hashes maintain records     @generated_keys.merge!({key => time.now})     @all_keys.merge!(@generated_keys) { |key, v1, v2| v1 }     return key   end 

and use generated keys here: (i need random pair selected , allotted user)

def get_available_key     if(generated_keys.empty?)       return "404. no keys available"     else       new_key = @generated_keys.to_a.sample(1)       @generated_keys.delete(new_key[0][0].to_s)       @blocked_keys.merge!({new_key[0][0].to_s => time.now})     end   end 

this how use in sinatra

api = keyserver.new '/block_key'    api.get_available_key end 

i tried solution mentioned in question when run part of sinatra server obtain internal server error: no implicit conversion array string

how make work? other method obtain random pair hash welcome.

to random element hash return hash patch hash

class hash   def sample(n)     hash[to_a.sample(n)]   end end 

then call

h = {a: 1, b: 2, c: 3}  h.sample(1) #=> {b: 2} h.sample(2)  #=> {:b=>2, :a=>1} 

note: used hash::[] compatibility purposes in ruby 2.x use to_h instead.

other think there might few more issues code , it's return values.

if refactor code sample code above not needed instead go something

def get_available_key   if(generated_keys.empty?)     {"error" => "404. no keys available"}   else     new_key = @generated_keys.keys.sample(1)     @generated_keys.delete(new_key)     @blocked_keys.merge!({new_key => time.now})[new_key]   end end 

this way respond hash object handling purposes , need not worry multidimensional arrays @ all.

i change initial code more

def create_new_key    key = securerandom.urlsafe_base64   purged_keys.include?(key) ? create_new_key  : key end def generate_key   key = create_new_key    #add new key hashes maintain records   @generated_keys.merge!({key => time.now})   @all_keys.merge!(@generated_keys) { |key, v1, v2| v1 }   key end def add_to_key_chain(length)   @generated_keys ||= {}   length.times      create_new_key   end end 

although don't know purged_keys method looks like.


Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -