Skip to content

Instantly share code, notes, and snippets.

@stephanwehner
Created May 18, 2017 21:39
Show Gist options
  • Save stephanwehner/9659c2e4c1d5e277ec0479d0bd09212d to your computer and use it in GitHub Desktop.
Save stephanwehner/9659c2e4c1d5e277ec0479d0bd09212d to your computer and use it in GitHub Desktop.
# Simple Key-Value store in Ruby
# Stephan Wehner, May 2017
#
# 2 sample sessions illustrate usage:
# In one terminal:
# $ ruby simple-key-value-store.rb
# In another terminal session:
#
# $ telnet localhost 3333
# Trying ::1...
# Connected to localhost.
# Escape character is '^]'.
# PUT abc 123
# OK abc
# GET abc
# 123
# PUT bbbb
# ERROR parsing PUT bbbb
# PUT bbb 3333
# OK bbb
# GET bbb
# 3333
# quit
# Connection closed by foreign host.
# $ telnet localhost 3333
# Trying ::1...
# Connected to localhost.
# Escape character is '^]'.
# GET bbb
# 3333
#######################################################
require 'socket'
server = TCPServer.new 3333
@store = {}
def handle_line(connection, line)
if line =~ /^PUT ([[:alnum:]]+) (.*)/
k, v = $1, $2
@store[k] = v
connection.puts "OK #{k}"
elsif line =~ /^GET ([[:alnum:]]+)\s*/
k = $1
connection.puts @store[k]
else
connection.puts "ERROR parsing #{line}"
end
end
while connection = server.accept do
while line = connection.gets do
break if line =~ /\Aquit/
handle_line connection, line
end
connection.close
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment