I would like to have a class and some attributes which you can either set during initialization or use its default value.
class Fruit
attr_accessor :color, :type
def initialize(color, type)
@color=color ||= 'green'
@type=type ||='pear'
end
end
apple=Fruit.new(red, apple)
The typical way to solve this problem is with a hash that has a default value. Ruby has a nice syntax for passing hash values, if the hash is the last parameter to a method.
A good overview is here: http://deepfall.blogspot.com/2008/08/named-parameters-in-ruby.html
Brian's answer is excellent but I would like to suggest some modifications to make it mostly meta:
Which outputs:
Of course this wouldn't be a perfect solution for everything but it gives you some ideas on making your code more dynamic.
More simple way:
Since Ruby 2.0 there is support of named or keyword parameters.
You may use:
Some interesting notes on this topic:
Even more tasty syntactic sugar:
I'd do it like this:
This way, you never have to worry about missing arguments--or their order--and you'll always have your default values right there.
.merge
will of course overwrite the default values if they're present.