sky-uk / ruby-bootcamp

Other
18 stars 22 forks source link

Enumerable #20

Open lashd opened 9 years ago

lashd commented 9 years ago

@joshnesbitt I'm thinking it would be nice for candidates to create their own collections and use Enumerable. Any ideas for an exercise?

joshnesbitt commented 9 years ago

What if we implmented a really simple finder interface for basic objects. Ask them to define a #find method that uses #select under the hood or something. Like this:

class PostCollection
  include Enumerable

  def add(post = {})
    @posts ||= []
    @posts << post
  end

  def each(&block)
    @posts.each(&block)
  end

  def where(conditions = {})
    select do |post|
      attribute = conditions.keys.first
      value = conditions.values.first
      post[attribute] == value
    end
  end
end

collection = PostCollection.new
collection.add(title: 'One', content: 'Post content...')
collection.add(title: 'Two', content: 'Post content...')
collection.add(title: 'Three', content: 'Post content...')
collection.add(title: 'Four', content: 'Post content...')

results = collection.where(title: 'One')

puts results.count
puts results.first[:title]
puts results.first[:content]
joshnesbitt commented 9 years ago

@lashd might be good just to do this as a quick workshop with some follow on exercises.

lashd commented 9 years ago

I think this is one of these 'aside' type works shops where it doesn't matter hugely if they don't receive it. It's handy definitely but maybe we don't need to write this one for V1 of the course?

joshnesbitt commented 9 years ago

Yup agree.