Skip to content

Instantly share code, notes, and snippets.

@danscotton
Forked from Integralist/Bad Design.rb
Last active August 29, 2015 13:57
Show Gist options
  • Save danscotton/9911710 to your computer and use it in GitHub Desktop.
Save danscotton/9911710 to your computer and use it in GitHub Desktop.
# - I've assumed you've separated the items into two arrays
# because you want to select those items at some point later.
# I've refactored to 'filter' the items on the way out, rather
# than filtering them on the way in.
# - Also added a :type method rather than class checking.
# - You could even use Set instead of [] here
class Foo
def initialize(initial_items = [])
@items = initial_items
end
def add(item)
@items << item
end
def a
select(:a)
end
def b
select(:b)
end
private
def select(type)
@items.select { |item| item.type == type }
end
end
# If you wanted to create more types in the future, say :c, you
# could dynamically generate the accessors?
class A
def initialize(name="Unknown")
@name = "A: #{name}"
@time = Time.now
end
def type
:a
end
end
class B
def initialize(name="Unknown")
@name = "B: #{name}"
@time = Time.now
end
def type
:b
end
end
foo = Foo.new
foo.add(A.new)
foo.add(B.new)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment