Skip to content

Instantly share code, notes, and snippets.

@ericsagnes
Created February 2, 2014 02:11
Show Gist options
  • Save ericsagnes/8762036 to your computer and use it in GitHub Desktop.
Save ericsagnes/8762036 to your computer and use it in GitHub Desktop.
require 'digest/sha1'
require 'csv'
require 'pp'
class ShaRand
attr_reader :data
def initialize
@data = {}
end
# add a hash to the hash database
def add( hash = nil )
hash ||= Digest::SHA1.hexdigest( Time.now.to_f.to_s ).upcase
@data[hash] = shorthand( hash )
end
# create a hash shorthand
def shorthand( hash )
shorthand = ''
hash.split('').each_with_index do |char, index|
shorthand += char
next if shorthand.length < 2
return shorthand unless @data.values.include?( shorthand )
end
end
# populate the database
def populate( limit )
limit.times{ |i| add }
end
# save to a csv
def to_csv( file )
CSV.open(file, "wb") do |csv|
@data.each_pair do |key, shorthand|
csv << [ key, shorthand ]
end
end
end
# load from a csv
def from_csv( file )
CSV.foreach(file) do |row|
add row.first
end
end
end
# simply populating a sharand database
def scenario1( limit = 100 )
sharand = ShaRand.new
sharand.populate( limit )
sharand.data
end
# populating a sharand database and save it to csv
def scenario2( limit = 100 )
sharand = ShaRand.new
sharand.populate( limit )
sharand.to_csv( 'sha1.csv' )
sharand.data
end
# load a csv database, add some values and save as a different csv:
def scenario3( limit = 100 )
sharand = ShaRand.new
sharand.from_csv( 'sha1.csv' )
sharand.populate( limit )
sharand.to_csv( 'sha1_2.csv' )
sharand.data
end
pp scenario1
pp scenario2
pp scenario3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment