Ruby when is initialize called




















We can see that the new method actually comes from Class. But then how does the initialize method gets called when we call new on a class? Turns out, Ruby internally calls initialize on the object passing all the arguments that were passed to new. As Ruby allows us to override any method, we can override the new class method as well. As expected, Ruby happily calls the overridden new method and no longer calls the initialize method because we did not call it from our definition of new.

It is clear that the new method is overridden by the DeprecationProxy class and it returns same object when the object has a falsey value. We know, those method calls look a little confusing.

We have a ton of examples that should clear that confusion up. The first argument to format is a string that will be used to format the output. Most of it is formatted exactly as it appears in the string. The remaining arguments are used as values for those format sequences. The most common types are:. We can use that sequence type to format the currency in our pay stubs. The results still show too many decimal places. We need to ensure the formatted value fills a minimum number of spaces, so that the columns align properly.

You can specify the minimum width after the percent sign in a format sequence. If the argument for that format sequence is shorter than the minimum width, it will be padded with spaces until the minimum width is reached. The minimum width of the entire number includes decimal places.

The width after the decimal point is the maximum number of digits to show. If a more precise number is given, it will be rounded up or down to fit in the given number of decimal places.

Could this be the key to fixing our pay stubs? But now we finally have a format sequence that will round a floating-point number to two decimal places:. Look at each of these Ruby statements, and write down what you think the result will be. Consider the result of the division operation, as well as the formatting that will be applied to it. What happened? What the heck is this nil thing? Ruby has a special value, nil , that represents nothing. That is, it represents the absence of a value.

You may recall that the p method calls inspect on each object before printing it. So, when you first create an instance of the Employee class, its name and salary instance variables have a value of nil. Is division really a method? In Ruby, the answer is yes; most mathematical operators are implemented as methods. When Ruby sees something like this in your code:. But while the Fixnum and Float classes define these operator methods, NilClass does not. And why should it?

You want an error to be raised, to bring your attention to the problem. It was a mistake when we forgot to set a salary for an Employee , for example. If we could set name and salary at the same time as we create an Employee instance, it would reduce the potential for errors. Ruby provides a mechanism to help with this situation: the initialize method. The initialize method is your chance to step in and make the object safe to use, before anyone else attempts to call methods on it.

When you call MyClass. Our initialize method now sets a default name of "Anonymous" and a default salary of 0. It would be better if we could supply a value other than these defaults. We can use this feature to let the caller of Employee. All we have to do is add name and salary parameters to initialize , and use them to set the name and salary instance variables.

And just like that, we can set name and salary via arguments to Employee. Since initialize is an ordinary method, it can utilize all the features of ordinary methods. And that includes optional parameters. Remember those from Chapter 2? We can specify default values when declaring the parameters. Then, we just assign those parameters to the instance variables normally. Your job is to take code snippets from the pool and place them into the blank lines in the code.

Your goal is to make code that will run and produce the output shown. Note: each thing from the pool can only be used once! A: They both serve the same basic purpose: to let the class prepare new instances for use. Q: Why do I have to call MyClass. Without new , there would be no object to initialize!

So we oversimplified a little bit; initialize does differ from an ordinary instance method in one respect. Q: Does MyClass. A: Actually, they did have one All Ruby classes inherit an initialize method from the Object superclass.

Q: But if Employee inherited an initialize method, why did we have to write our own? A: The initialize from Object takes no arguments, and basically does nothing.

Q: Can I return a value from an initialize method? A: You can, but Ruby will ignore it. The initialize method is intended solely for setting up new instances of your class, so if you need a return value, you should do that elsewhere in your code. We have bad news for you: since your initialize method assigns directly to the name and salary instance variables, bad data has a new way to sneak in!

We could get our initialize method to validate its parameters by adding the same validation code to the initialize method But duplicating code like that is a problem.

There would be different rules for setting the name, depending on how you set it! That would let us set the name and salary instance variables. It would also let us run the validation code, without duplicating it! And to call an instance method, we usually use the dot operator. Besides, amy is out of scope within the initialize method. The problem is, what do we put there? How do you refer to the current instance from inside an instance method? Ruby has an answer: the self keyword.

Within instance methods, self always refers to the current object. Within instance methods, the keyword self refers to the current object. It may be preferable to require that each piece of fruit have its kind specified at the time of its creation. To do this, we would add a formal argument to the initialize method. For reasons we won't get into here, arguments you supply to new are actually delivered to initialize.

If we want to be more considerate, we can use the argument if it is given, or fall back to default values otherwise. The argument list must be arranged so that those with default values come last.



0コメント

  • 1000 / 1000