0

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

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

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.