Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Class reopening is a good example of this. Here's a simple example:</p> <pre><code>class Integer def moxy if self.zero? self - 2 elsif self.nonzero? self + 2 end end end puts 10.moxy </code></pre> <p>By reopening a standard Ruby class - Integer - and defining a new method within it called 'moxy', we can perform a newly defined operation directly on a number. In this case, I've defined this made up 'moxy' method to subtract 2 from the Integer if it's zero and add two if it's nonzero. This makes the moxy method available to all objects of class Integer in Ruby. (Here we use the 'self' keyword to get the content of the integer object). </p> <p>As you can see, it's a very powerful feature of Ruby.</p> <p>EDIT: Some commenters have questioned whether this is really <a href="http://en.wikipedia.org/wiki/Reflection_(computer_science)" rel="nofollow noreferrer">reflection</a>. In the English language the word reflection refers to looking in on your own thoughts. And that's certainly an important aspect of reflection in programming also - using Ruby methods like is_a, kind_of, instance_of to perform runtime self-inspection. But reflection also refers to the the ability of a program to modify its own behavior at runtime. Reopening classes is one of the key examples of this. It's also called <a href="http://en.wikipedia.org/wiki/Monkey_patch" rel="nofollow noreferrer">monkey patching</a>. It's not without its risks but all I am doing is describing it here in the context of reflection, of which it is an example.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload