Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way to initialize a Class in Ruby with different parameters and default values?

Tags:

oop

class

ruby

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) 
like image 556
Istvan Avatar asked Dec 29 '10 13:12

Istvan


People also ask

What does initialize method do in Ruby?

The initialize method is useful when we want to initialize some class variables at the time of object creation. The initialize method is part of the object-creation process in Ruby and it allows us to set the initial values for an object.

How do you pass a default parameter in Ruby?

The syntax for declaring parameters with default values In order to define a default value for a parameter, we use the equal sign (=) and specify a value to which a local variable inside the method should reference.

What is def initialize?

Definition of initialize transitive verb. : to set (something, such as a computer program counter) to a starting position, value, or configuration.


1 Answers

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.

class Fruit   attr_accessor :color, :type    def initialize(params = {})     @color = params.fetch(:color, 'green')     @type = params.fetch(:type, 'pear')   end    def to_s     "#{color} #{type}"   end end  puts(Fruit.new)                                    # prints: green pear puts(Fruit.new(:color => 'red', :type => 'grape')) # prints: red grape puts(Fruit.new(:type => 'pomegranate')) # prints: green pomegranate 

A good overview is here: http://deepfall.blogspot.com/2008/08/named-parameters-in-ruby.html

like image 137
Brian Clapper Avatar answered Sep 22 '22 16:09

Brian Clapper