Created
March 5, 2014 04:12
-
-
Save adomokos/9361006 to your computer and use it in GitHub Desktop.
Recognizing Ruby's group_by in the imperative code
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
class Location | |
attr_reader :city, :user | |
def initialize(city, user) | |
@city = city | |
@user = user | |
end | |
end | |
class User | |
attr_reader :name | |
def initialize(name=nil) | |
@name = name | |
end | |
end | |
class FindsEmployeesByLocations | |
def self.from(employee_locations=[]) | |
employee_locations.group_by(&:city) | |
# locations = Hash.new | |
# employee_locations.each do |location| | |
# | |
# if !locations.key?(location.city) | |
# locations[location.city] = Array.new; | |
# end | |
# | |
# locations[location.city].push(location); | |
# end | |
# | |
# return locations | |
end | |
end | |
describe FindsEmployeesByLocations do | |
let(:john) { User.new("John") } | |
let(:james) { User.new("James") } | |
let(:kate) { User.new("Kate") } | |
let(:employee_locations) do | |
[ | |
Location.new("Chicago", john), | |
Location.new("Chicago", kate), | |
Location.new("New York", james) | |
] | |
end | |
context "when the employee locations collection is empty" do | |
specify "employees by locations is empty" do | |
expect(FindsEmployeesByLocations.from([])).to be_empty | |
end | |
end | |
context "when there are 3 employees with 2 locations" do | |
subject { FindsEmployeesByLocations.from(employee_locations) } | |
it "has only 2 locations" do | |
expect(subject.keys.count).to eq(2) | |
end | |
specify "first locations has 2 users" do | |
expect(subject.keys.first).to eq("Chicago") | |
chicago_location = subject["Chicago"] | |
expect(chicago_location.count).to eq(2) | |
expect(chicago_location.map(&:user).map(&:name)).to eq(%w(John Kate)) | |
end | |
specify "last locations has 1 user" do | |
expect(subject.keys.last).to eq("New York") | |
new_york_location = subject["New York"] | |
expect(new_york_location.count).to eq(1) | |
expect(new_york_location.first.user.name).to eq("James") | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment