Search code examples
rubyclassclass-method

How to pass objects to the class method


I have the following class method that uses default classes if no provided:

def self.make_sandwich(bread = Bread, butter = Butter, cheese = Cheese)
  ...
end

So I can call it and pass a new class of bread called MyBread

[class].make_sandwich(MyBread)

But how can I pass a bread and cheese without butter? I know I could change the order or use the attr_accessor to use the default class if no provided, but assume I cant modify that code that way


Solution

  • If you're on ruby 2.0 you can use keyword arguments.

    If you're on older ruby, you can use hash opts parameter.

    def self.make_sandwich(opts = {:bread => Bread, 
                                   :butter => Butter, 
                                   :cheese => Cheese})
    
      bread_to_use = opts[:bread]
    end
    
    make_sandwich(:bread => some_bread,
                  :cheese => some_cheese)
    

    Alternatively, you can set default values in the method's body and then just pass nil in the method call.

    def self.make_sandwich(bread = nil, butter = nil, cheese = nil)
      bread ||= Bread
      butter ||= Butter
      cheese ||= Cheese
      ...
    end
    
    make_sandwich(bread, nil, cheese)