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

« Newer Snippets
Older Snippets »
Showing 31-40 of 43 total

Creating multi-dimensional hashes in Ruby

The use of var = keys.shift (instead of var = keys_clone || keys.shift) will produce an alternative output!


class Hash
  def mdh(*mkeys)
     value = mkeys.pop
     count = 0
     mdhash = lambda { |*keys|
                   count += 1
                   keys_clone = keys.clone if count == 1 # keys_clone will return nil for count > 1 in Hash.new
                   Hash.new(var = keys_clone || keys.shift).update(var => mdhash[*keys] || value) unless keys.empty? 
                 }
     mdhash.call(*mkeys)
  end
end

h = Hash.new.mdh(1, 2, 3, 4, "value")

puts h.inspect  # {[1, 2, 3, 4]=>{1=>{2=>{3=>{4=>"value"}}}}}

k = [1, 2, 3, 4]
puts h.has_key?(k)
puts h[k][k[0]][k[1]][k[2]][k[3]]  # value


     

US State Abbreviations to Full name

# US State abbreviations to full name
# state_name = state_abbr.[]("MI")

state_abbr = {
  'AL' => 'Alabama',
  'AK' => 'Alaska',
  'AS' => 'America Samoa',
  'AZ' => 'Arizona',
  'AR' => 'Arkansas',
  'CA' => 'California',
  'CO' => 'Colorado',
  'CT' => 'Connecticut',
  'DE' => 'Delaware',
  'DC' => 'District of Columbia',
  'FM' => 'Micronesia1',
  'FL' => 'Florida',
  'GA' => 'Georgia',
  'GU' => 'Guam',
  'HI' => 'Hawaii',
  'ID' => 'Idaho',
  'IL' => 'Illinois',
  'IN' => 'Indiana',
  'IA' => 'Iowa',
  'KS' => 'Kansas',
  'KY' => 'Kentucky',
  'LA' => 'Louisiana',
  'ME' => 'Maine',
  'MH' => 'Islands1',
  'MD' => 'Maryland',
  'MA' => 'Massachusetts',
  'MI' => 'Michigan',
  'MN' => 'Minnesota',
  'MS' => 'Mississippi',
  'MO' => 'Missouri',
  'MT' => 'Montana',
  'NE' => 'Nebraska',
  'NV' => 'Nevada',
  'NH' => 'New Hampshire',
  'NJ' => 'New Jersey',
  'NM' => 'New Mexico',
  'NY' => 'New York',
  'NC' => 'North Carolina',
  'ND' => 'North Dakota',
  'OH' => 'Ohio',
  'OK' => 'Oklahoma',
  'OR' => 'Oregon',
  'PW' => 'Palau',
  'PA' => 'Pennsylvania',
  'PR' => 'Puerto Rico',
  'RI' => 'Rhode Island',
  'SC' => 'South Carolina',
  'SD' => 'South Dakota',
  'TN' => 'Tennessee',
  'TX' => 'Texas',
  'UT' => 'Utah',
  'VT' => 'Vermont',
  'VI' => 'Virgin Island',
  'VA' => 'Virginia',
  'WA' => 'Washington',
  'WV' => 'West Virginia',
  'WI' => 'Wisconsin',
  'WY' => 'Wyoming'
}

Average US State Locations

# A hash table of average US State Locations (latitude, longitude)
# MI_Location = state_locations.[]("MI")

state_locations = {
  'AK' => [61.3850,-152.2683],
  'AL' => [32.7990,-86.8073],
  'AR' => [34.9513,-92.3809],
  'AS' => [14.2417,-170.7197],
  'AZ' => [33.7712,-111.3877],
  'CA' => [36.1700,-119.7462],
  'CO' => [39.0646,-105.3272],
  'CT' => [41.5834,-72.7622],
  'DC' => [38.8964,-77.0262],
  'DE' => [39.3498,-75.5148],
  'FL' => [27.8333,-81.7170],
  'GA' => [32.9866,-83.6487],
  'HI' => [21.1098,-157.5311],
  'IA' => [42.0046,-93.2140],
  'ID' => [44.2394,-114.5103],
  'IL' => [40.3363,-89.0022],
  'IN' => [39.8647,-86.2604],
  'KS' => [38.5111,-96.8005],
  'KY' => [37.6690,-84.6514],
  'LA' => [31.1801,-91.8749],
  'MA' => [42.2373,-71.5314],
  'MD' => [39.0724,-76.7902],
  'ME' => [44.6074,-69.3977],
  'MI' => [43.3504,-84.5603],
  'MN' => [45.7326,-93.9196],
  'MO' => [38.4623,-92.3020],
  'MP' => [14.8058,145.5505],
  'MS' => [32.7673,-89.6812],
  'MT' => [46.9048,-110.3261],
  'NC' => [35.6411,-79.8431],
  'ND' => [47.5362,-99.7930],
  'NE' => [41.1289,-98.2883],
  'NH' => [43.4108,-71.5653],
  'NJ' => [40.3140,-74.5089],
  'NM' => [34.8375,-106.2371],
  'NV' => [38.4199,-117.1219],
  'NY' => [42.1497,-74.9384],
  'OH' => [40.3736,-82.7755],
  'OK' => [35.5376,-96.9247],
  'OR' => [44.5672,-122.1269],
  'PA' => [40.5773,-77.2640],
  'PR' => [18.2766,-66.3350],
  'RI' => [41.6772,-71.5101],
  'SC' => [33.8191,-80.9066],
  'SD' => [44.2853,-99.4632],
  'TN' => [35.7449,-86.7489],
  'TX' => [31.1060,-97.6475],
  'UT' => [40.1135,-111.8535],
  'VA' => [37.7680,-78.2057],
  'VI' => [18.0001,-64.8199],
  'VT' => [44.0407,-72.7093],
  'WA' => [47.3917,-121.5708],
  'WI' => [44.2563,-89.6385],
  'WV' => [38.4680,-80.9696],
  'WY' => [42.7475,-107.2085]
}

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:

class Hash
  def +(add)
    temp = {}
    add.each{|k,v| temp[k] = v}
    self.each{|k,v| temp[k] = v}
    temp
  end
end


Now you can do stuff like:

x = { :a => 1 }
y = { :b => 2 }

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


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

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

Parsing a query string with String#scan into a Hash

For more information on the desired hash output, etc. see:

http://redhanded.hobix.com/inspect/injectingAHashBackwardsAndTheMergeBlock.html


qs = "post[id]=4&post[nick]=_why&post[message]=GROSS & FOO!&a=1"  # query string

hash1 = {}
hash2 = {}
resulthash = {}
count = 0

qs.scan(/(post|a)(\[|=)(.*?)(?=(&post\[|&a=|$))/) {

var = $1 << $2 << $3  


case var

when /^(post)\[(.*?)\]=(.*?)$/ then 
               count += 1
               postnum = $1 << count.to_s
               hash1.update(postnum => {$2 => $3})

when /^(a)=(.*?)$/ then resulthash.update($1 => $2)

end


}

hash1.each_pair {|k, v| hash2.update(v)}
resulthash.update("post" => hash2)

puts resulthash.inspect 

Zip two Arrays together into a Hash

Found this here:

http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/122906
 
def Hash.from_pairs_e(keys,values)
  hash = {}
  keys.size.times { |i| hash[ keys[i] ] = values[i] }
  hash
end 

Array to Hash in Ruby

Inspired by something Ryan Carver was trying to do:

a = [1, 2, 3]
Hash[*a.collect { |v|
    [v, v*2]
}.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
newhash = oldhash.scan(/./).map{|t1| t2 = t1[0] % 36; t2 < 26 ? (t2+65).chr : (t2+22).chr }.join

Perl
$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 ;-)

Random key from Ruby Hash (faster)

I needed a Ruby Hash class that could extract a random key from the keys that have not been extracted before. Plus that the class should be re-entrant...

I found baby's class, but it was not working (at least not in Ruby 1.8.x). I made it work (slight changes), and I added the keys_not_used to make it work faster (baby's random would cycle almost forever on large lists). But I would say all credit should go to the original author, who did all the hard work.

Without further ado, here is the new version:
class RandomHash < Hash 

   @keys_used = nil 
  
   def random_key 
      if @keys_used == nil then
         @keys_used = Hash.new 
      else
         @keys_used = Hash.new if @keys_used.size == self.size
      end
      
      if (@keys_used.size == 0) then
         pos = rand(self.size)
         key = self.keys[pos]
      else
         @keys_not_used = Hash.new
     	 self.keys.each{ |key|
         	if (! @keys_used.include?(key)) then
            	    @keys_not_used[key] = 1
         	end
	     }
	     pos = rand(@keys_not_used.size)
	     key = @keys_not_used.keys[pos]
	  end
	  
      @keys_used[key] = 1
      return key 
   end 
end 

# Test code
$sources = Hash.new
$RandomSources = RandomHash.new

begin

   (1..10).each{ |val|
      $sources["#{val}"] = 1
   }
   
   $sources.each { |src|
      puts "Src=#{src}"
      $RandomSources[src] = 1
   }

   RandomKeys = Hash.new
   (0..$sources.length).each{ |index| # one more than all values
      key = $RandomSources.random_key
      print "Extracted #{key} ... It's a"
      if (!RandomKeys.has_key?(key)) then
         puts " NEW key!"
         RandomKeys[key] = 1
      else
         puts "n OLD key!"
      end
   }
end

finding md5 in python

import md5
hash = md5.new("Hello world").digest()

more info here http://docs.python.org/lib/module-md5.html
« Newer Snippets
Older Snippets »
Showing 31-40 of 43 total