2009年12月19日 星期六

Ruby functions

p method:
  • The p method prints out an internal representation of an object. Using it, we can see that in each case our parameters got transferred into the object's state, ending up as instance variables.
puts method:
  • puts method simply writes strings to your program's standard output. When you pass it an object based on a class you wrote, it doesn't really know what to do with it, so it uses a very simple expedient: it writes the name of the object’s class, followed by a colon and the
    object’s unique identifier (a hexadecimal number).
to_s method:
  • Ruby has a standard message, to_s, that it sends to any object it wants to render as a string.
  • We can override the default implementation of to_s to give us a better rendering of our objects via puts method.
attr_reader:
  • Because writing accessor methods is such a common idiom, Ruby provides a convenient shortcut. attr_reader creates these attribute reader methods for you
  • There’s a common misconception, particularly among people who come from languages such as Java and C#, that the attr_reader declaration somehow declares instance variables. It doesn’t. It creates the accessor methods, but the variables themselves don’t need to be declared—they just pop into existence when you use them. Ruby completely decouples instance variables and accessor methods.

沒有留言:

張貼留言