Skip to content

Instantly share code, notes, and snippets.

@daguar
Created August 8, 2012 21:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daguar/3298859 to your computer and use it in GitHub Desktop.
Save daguar/3298859 to your computer and use it in GitHub Desktop.
Falling for Ruby: "Holy Crap!" Edition
=begin
Every day I use Ruby I see more and more why people become evangelists.
Take today: I was toying with evaluating different approaches to match two
data sources (API results and a giant local database), and I realized,
"wait! this is a job for yield!"
So I wrote a pleasant little module with a function that:
- Takes a block which attempts to match an API object to rows in the
database
- Returns a success rate (defined as the %age of 1-to-1 matches) as well
as a distribution (e.g., 20 results returned no match, and 40 returned 2
matches)
PS -- my first gist!
=end
# Example usage
[2] pry(main)> MatchingExperiments.try_approach { |api_restaurant| Restaurant.find_all_by_phone(api_restaurant["phone_number"]).length }
=> {:success_rate=>0.63, :distribution=>{0=>91, 1=>163, 2=>5, 4=>1}}
# matching_experiments.rb
require 'json'
module MatchingExperiments
# This is my API sampled test data
APITESTDATA = JSON.parse(File.open("test_data_json_touse.txt","r").read)
def self.try_approach
counts = Hash.new
APITESTDATA.each do |api_restaurant|
number_of_results = yield(api_restaurant)
if counts[number_of_results] != nil
counts[number_of_results] += 1
else
counts[number_of_results] = 1
end
end
success_rate = ( counts[1].to_f / counts.inject(0) { |sum,item| sum + item[1] } ).round(2)
return Hash[success_rate: success_rate, distribution: counts]
end
end
@steveklabnik
Copy link

Awesome! one tiny tip: you can do this:

counts[number_of_results] ||= 0
counts[number_of_results] += 1

instead of this:

if counts[number_of_results] != nil
  counts[number_of_results] += 1
else
  counts[number_of_results] = 1
end

@ivanacostarubio
Copy link

@steveklabnik <3 refactoring!

@daguar
Copy link
Author

daguar commented Aug 9, 2012

Thanks, @steveklabnik !

(I had a feeling I could refactor that bit, but was pretty much overloaded with joy by the vaguely-proper use of Ruby closures I'd stumbled my way through.)

@carols10cents
Copy link

RUBYLOVE!!!!

@syntacticsugar
Copy link

hmmm... i see you went from... highly functional... to....

(pause)...

procedural.

(draws various judgments on your nature)

@daguar
Copy link
Author

daguar commented Aug 25, 2012

Ruby values clarity and legibility, and I do too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment