Rich_F
Rich_F

Reputation: 2056

Ruby Class Definition with Optional Parameters Possible?

I'm looking to see if there's a way of having optional arguments in a class definition, destined for the initialize method.

class MyClass
    def initialize(parameters)
        # blah blah do something
    end
end

a = MyClass.new('alpha')    # works fine
b = MyClass.new             # throws ArgumentError

And the error:

'initialize': wrong number of arguments (given 0, expected 1) (ArgumentError)

I'm looking for a way to have optional parameters. Sometimes I want to create an object with no parameters, but don't want to trip an error. Sometimes I want to provide parameters and have them be used properly in the initialize method.

Can this be done, or are these my two options?

Upvotes: 0

Views: 5042

Answers (1)

m26a
m26a

Reputation: 1413

Yes, you can do this just like a normal method definition. You will have to supply a default value for the argument you want to be optionally. This means that if a value for the argument isn’t supplied, the default value will be used instead.

class MyClass
  def initialize(value = "default value")
    @value = value
  end
end

Also, you can use:

def initialize(*parameters)

parameters will be an array with the values you have passed, or an empty array if you pass no values.

Upvotes: 1

Related Questions