# A little toy file demonstrating how to build chainable # data transformations that reveal some amount of intent # through named extracted methods. # # Kudos to @mfeathers for giving me the idea to try this # # Copyright Test Double, LLC, 2016. All Rights Reserved. require_relative "marketing_refinements" class MarketResearch # Vanilla / Anonymous / Primitive approach to chaining def income_by_smoking(data) Hash[ data.reject {|p| p[:income] < 10_000 }. group_by { |p| p[:smoker] }. map { |(is_smoker, people)| [ is_smoker ? :smokers : :non_smokers, people.map {|p| p[:income]}.reduce(:+).to_f / people.size ] } ] end # Refined approach to tacking named domain abstractions onto Array/Hash using MarketingRefinements def income_by_smoking_fancy(data) data.exclude_incomes_under(10_000). separate_people_by(:smoker). average_income_by_smoking end end DATA = [ {age: 19, smoker: false, income: 10_000, education: :high_school}, {age: 49, smoker: true, income: 120_000, education: :bachelors}, {age: 55, smoker: false, income: 400_000, education: :masters}, {age: 23, smoker: true, income: 10_000, education: :bachelors}, {age: 70, smoker: false, income: 70_000, education: :phd }, {age: 34, smoker: false, income: 90_000, education: :masters}, {age: 90, smoker: true, income: 0, education: :high_school}, ] original_result = MarketResearch.new.income_by_smoking(DATA) fancy_result = MarketResearch.new.income_by_smoking_fancy(DATA) puts <<-MSG Original result: #{original_result} Fancy result: #{fancy_result} MSG