Skip to content

Instantly share code, notes, and snippets.

@petehuang
Created October 9, 2013 16:02
Show Gist options
  • Save petehuang/6903646 to your computer and use it in GitHub Desktop.
Save petehuang/6903646 to your computer and use it in GitHub Desktop.
Thumbtack programming challenge - Simple Database in Ruby before transactional block support
class SimpleDatabase
attr_accessor :database
def initialize
@database = {} #our database!
end
def set(name, value)
database[name] = value #write the new value to the database
end
def get(name)
if database[name]
puts database[name] #return the saved value
else puts 'NULL' #unless there is no value there
end
end
def unset(name)
database.delete(name) #delete the current value in the database
end
def numequalto(value)
puts database.values.count(value) #count how many pairs have the value
end
def evaluate_data_command(input)
command = input.split(' ')
valid = ["SET", "GET", "UNSET", "NUMEQUALTO"]
abort() if command[0] == "END"
if valid.include?(command[0])
case command[0]
when "SET"
set(command[1], command[2])
when "GET"
get(command[1])
when "UNSET"
unset(command[1])
when "NUMEQUALTO"
numequalto(command[1])
end
else
puts "NO METHOD FOUND"
end
end
end
db = SimpleDatabase.new
STDIN.each_line do |l|
db.evaluate_data_command(l)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment