
Saved by Harold T. Harper
The Well-Grounded Rubyist
Saved by Harold T. Harper
Now, scenario 2. The superclass of Class is Module. Instances of Class therefore have access to the instance methods defined in Module; among these are the attr_accessor family of methods. That’s why we can write class Ticket attr_reader :venue, :date attr_accessor :price attr_reader and attr_accessor go directly to the class object Ticket, which i
... See moreIn an assignment with a variable name on the left and an object on the right, the variable receives a reference to the object. In an assignment from one variable to another (abc = str), the variable on the left receives a copy of the reference stored in the variable on the right, with the result that both variables now contain references to the sam
... See moreTo see a list of innate methods, you can call the methods method (and throw in a sort operation, to make it easier to browse visually): p Object.new.methods.sort
To understand where classes get their methods, think about where objects in general get their methods (minus modules, which we haven’t explored yet): From their class From the superclass and earlier ancestors of their class From their own store of singleton methods (the “talk” in def obj.talk)
Despite what might be your first impression, Ruby’s single inheritance doesn’t restrict you: Ruby provides modules, which are bundles of programming functionality similar to classes (except that they don’t have instances), that you can easily graft onto your class’s family tree to provide as many methods for your objects as you need.
Calling methods (that is, sending messages to objects) usually involves the dot notation: obj.talk ticket.venue "abc".capitalize
A newly created BasicObject instance has only 8 instance methods—whereas a new instance of Object has 58.
Storing a program in a single file can be handy, but it starts to be a liability rather than an asset when you’ve got hundreds or thousands—or hundreds of thousands—of lines of code. Somewhere along the line, breaking your program into separate files starts to make lots of sense. Ruby facilitates this process with the require and load methods. We’l
... See moreYou can determine in advance (before you ask the object to do something) whether the object knows how to handle the message you want to send it, by using the respond_to? method. This method exists for all objects; you can ask any object whether it responds to any message. respond_to? usually appears in connection with conditional (if) logic: obj =
... See more