Skip to content

Instantly share code, notes, and snippets.

@gerardogc2378
Created March 29, 2021 19:44
Show Gist options
  • Save gerardogc2378/878c3041e20e77da48fe0b46ab0352f5 to your computer and use it in GitHub Desktop.
Save gerardogc2378/878c3041e20e77da48fe0b46ab0352f5 to your computer and use it in GitHub Desktop.
##
# Hello hello!
#
# This is meant to be a quick (and fun?) sense-check of your Ruby!
#
# Notes:
# 1. Feel free to download the CSV locally paste into irb or run this with `ruby requests.rb`!
# 2. We're loosely available to field questions on recruiting+fullstack@trychameleon.com
# 3. Don't overanalyze your implementation/formatting/variable names/etc. do what comes naturally to you
# 4. More than anything, thanks for taking the time to work through this! -BN
#
#require 'uri'
#require 'net/http'
require 'csv'
require 'time'
#uri = URI('requests.csv'); nil
#res = Net::HTTP.get_response(uri); nil
csv = CSV.parse(File.read('requests.csv'), headers: true); nil
#csv.shift
#=> ["request id","timestamp","user id","method","path","response time","db time"]
#csv.sample
#=> ["864197", "2028-03-23T02:44:49.192Z", "5fb3392954558f806fe97441", "PATCH", "/profiles/:id", "20ms", "7ms"]
##
# 1. average response time
avg = csv.by_col[5].map{|x| x.gsub("ms","").to_i}.reduce(0){|sum,num| sum + num} / csv.by_col[5].count
puts "AVG: #{avg}ms"
# =>
##
# 2. number of users online
puts "#{csv.by_col[5].count} users online"
# =>
##
# 3. ids of the 5 slowest requests
puts csv.select {|x| x.to_h["response time"].gsub("ms","").to_i < avg}.map(&:to_h).sort{|a,b| a["response time"].gsub("ms","").to_i <=> b["response time"].gsub("ms","").to_i}.take(5)
# =>
##
# Bonus question: Imagine you received this CSV as a "stream" and had, at any point in parsing the file, to
# output the "current top 5 slowest requests".
#
# 4. What is the state of your data structure(s) at row 75121.
puts csv.select {|x| x.to_h["response time"].gsub("ms","").to_i < avg and x.to_h["request id"].to_i < 75121}.map(&:to_h).sort{|a,b| a["response time"].gsub("ms","").to_i <=> b["response time"].gsub("ms","").to_i}.take(5)
#=>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment