Skip to content

Instantly share code, notes, and snippets.

@lisovskyvlad
Last active July 29, 2018 08:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lisovskyvlad/8ccce220f4e24621e9c45dcd4ca642ea to your computer and use it in GitHub Desktop.
Save lisovskyvlad/8ccce220f4e24621e9c45dcd4ca642ea to your computer and use it in GitHub Desktop.
Ruby solution for the task mentioned in the article http://grishaev.me/why-clj
class MiddleRate
attr_reader :data
def initialize(data)
@data = data
end
def call
# age rates got { 18 => [30, 15], 50 => [35] }
age_rates = data.each_with_object(memory_hash) do |data_item, acc|
acc[data_item[:age]].push(data_item[:rate])
end
age_rates.reduce({}) do |acc, (age, rates)|
acc.merge(age => rates.reduce(:+).to_f / rates.count)
end
end
private
def memory_hash
Hash.new { |hash, key| hash[key] = [] }
end
end
require './middle_rate.rb'
RSpec.describe MiddleRate do
subject(:middle_rate) { described_class.new(data) }
let(:data) do
[{ age: 18, rate: 30 },
{ age: 18, rate: 15 },
{ age: 50, rate: 35 }]
end
let(:expected_output) do
{ 18 => 22.5, 50 => 35.0 }
end
it 'computes the middle rate' do
expect(middle_rate.call).to eq expected_output
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment