質問

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

役に立ちましたか?

解決

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)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top