Reputation: 2130
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
Upvotes: 0
Views: 45
Reputation: 230296
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)
Upvotes: 2