Skip to content

Instantly share code, notes, and snippets.

@adomokos
Created March 5, 2014 04:12
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 adomokos/9361006 to your computer and use it in GitHub Desktop.
Save adomokos/9361006 to your computer and use it in GitHub Desktop.
Recognizing Ruby's group_by in the imperative code
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