0

I am trying to remove a Silverware class inside of the @contents array by rewriting the method "remove_item" inside the drawer class. This method should takes a parameter of the name of the @type of the silverware.

class Drawer
attr_reader :contents
    def initialize
        @contents = []
    end
    def add_item(item)
        @contents << item
    end
    def remove_item(item = @contents.pop)
        @contents.delete(item)   # I have to fix this.
    end
end

class Silverware
    attr_reader :type
        def initialize(type, clean = true)
          @type = type
        end
end

silverware_drawer = Drawer.new    # creating new drawer
silverware_drawer.add_item(Silverware.new("spoon"))    # adding silverware
p silverware_drawer.contents    # I get this >> [#<Silverware:0x007f84aa091ad8 @type="spoon",     @clean=true>]

p silverware_drawer.remove_item("spoon")    # removing spoon
p silverware_drawer.contents    # Show drawer and I still get [#<Silverware:0x007f84aa091ad8 @type="spoon",     @clean=true>]

Any helps would be greatly appreciated! Thank you in advance!

1 Answer 1

1

You are not passing in the object. You are just passing in the type. So you have to find the item with type "spoon" and delete it from the array

def remove_item(item)
   @contents.delete(@contents.find{|content| content.type == item})
end
Sign up to request clarification or add additional context in comments.

1 Comment

or @contents = @contents.reject { |content| content.type == item } or @contents.reject! { |content| content.type == item }; @contents. (Recall that with reject!, nil is returned if no elements are rejected.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.