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.