Created
August 8, 2012 21:17
-
-
Save daguar/3298859 to your computer and use it in GitHub Desktop.
Falling for Ruby: "Holy Crap!" Edition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
=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 <3 refactoring!
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.)
RUBYLOVE!!!!
hmmm... i see you went from... highly functional... to....
(pause)...
procedural.
(draws various judgments on your nature)
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
Awesome! one tiny tip: you can do this:
instead of this: