Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Peter Cooperx http://www.petercooper.co.uk/

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS 

Addition for hashes in Ruby

Why, oh, why is there no addition for hashes in Ruby? 'update' can do the trick, but only returns what was updated, rather than the whole updated hash. It also forces an update rather than being passive.

Sometimes you only want to temporarily do an add, and this is how I pulled it off:

   1  class Hash
   2    def +(add)
   3      temp = {}
   4      add.each{|k,v| temp[k] = v}
   5      self.each{|k,v| temp[k] = v}
   6      temp
   7    end
   8  end


Now you can do stuff like:

   1  x = { :a => 1 }
   2  y = { :b => 2 }
   3  
   4  # x + y => { :a => 1, :b => 2 }, but x and y are untouched
   5  # x + { :c => 3 } => { :a => 1, :c => 3 }


If you want to force an add, it's easy:

   1  x += y => { :a => 1, :b => 2 } (this is now what x contains)

Array to Hash in Ruby

Inspired by something Ryan Carver was trying to do:

   1  a = [1, 2, 3]
   2  Hash[*a.collect { |v|
   3      [v, v*2]
   4  }.flatten]


It's not as foolproof as his solution, however!

User friendly hashes with only upper case characters and digits

I need a fast, user friendly hash. This means I want it to be only capital letters and digits. No symbols that people can't pronounce, and no mixed case to be misunderstood on the phone, etc. Use a hashing method like MD5 or SHA1 first, and then apply this..

Ruby
   1  newhash = oldhash.scan(/./).map{|t1| t2 = t1[0] % 36; t2 < 26 ? (t2+65).chr : (t2+22).chr }.join

Perl
   1  $newhash = join "", map { $t1 = ord($_) % 36; $t1 < 26 ? chr($t1+65) : chr($t1+22) } split(//, $oldhash);

This turns any hash into only using [A-Z0-9]. Even a 8 character hash/key using [A-Z0-9] results in 2,821,109,907,456 combinations ;-)
« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS