The Fruit class in the previous section has two real variables, indicating the Fruit type and status respectively. it was not until we wrote a customized inspect method for this class that we knew it would not give a reasonable explanation of a fruit with a lack of attributes. fortunately, Ruby provides a method that allows real variables to always be initialized.
Initalize Method
When Ruby creates a new object, it always looks for a method named initialize and executes it. therefore, we can simply add the default value to the Real Variable through an initialize method, so that the inspect method has something to say.
Ruby> class Fruit
| Def initialize
| @ Kind = "apple"
| @ Condition = "ripe"
| End
| End
Nil
Ruby> f4 = Fruit. new
"A ripe apple"
Change the default value to the required
In many cases, the default value does not mean much. Is it really the default fruit? It may be a better way to set requirements for the type of fruit when it is created. to do this, we must add a formal parameter to the initialize method. for some reasons not mentioned here, the parameter you passed to new is actually passed to initialize.
Ruby> class Fruit
| Def initialize (k)
| @ Kind = k
| @ Condition = "ripe"
| End
| End
Nil
Ruby> f5 = Fruit. new "mango"
"A ripe mango"
Ruby> f6 = Fruit. new
ERR: (eval): 1: in 'initialize': wrong # of arguments (0 for 1)
Elastic Initialization
As we can see above, once a parameter is associated with an initialize method, it cannot be saved without errors. if you want to consider it carefully, you can use it when giving it a parameter; otherwise, the default value is used.
Ruby> class Fruit
| Def initialize (k = "apple ")
| @ Kind = k
| @ Condition = "ripe"
| End
| End
Nil
Ruby> f5 = Fruit. new "mango"
"A ripe mango"
Ruby> f6 = Fruit. new
"A ripe apple"
You can use the default parameter in any method, not just the initialize. parameter table (argument list) must end with the parameter with the default value.
Sometimes it is helpful to provide multiple object initialization methods. although beyond the scope of this tutorial, Ruby provides object reflection and variable-length argument lists, which effectively promotes method overloading.