Jump to content
Wikibooks The Free Textbook Project

Ruby Programming/Reference/Predefined Classes

From Wikibooks, open books for an open world

In ruby even the base types (also predefined classes) can be hacked.[1] In the following example, 5 is an immediate,[2] a literal, an object, and an instance of Fixnum.

classFixnum
aliasother_sto_s
defto_s()
a=self+5
returna.other_s
end
end
a=5
putsa.class## prints Fixnum
putsa## prints 10 (adds 5 once)
puts0## prints 5 (adds 5 once)
puts5## prints 10 (adds 5 once)
puts10+0## prints 15 (adds 5 once)
b=5+5
putsb## puts 15 (adds 5 once)

Footnotes

[edit | edit source ]
  1. ^ Which means the 4 VALUE bytes are not a reference but the value itself. All 5 have the same object id (which could also be achieved in other ways).
  2. ^ Might not always work as you would like, the base types don't have a constructor (def initialize), and can't have singleton methods. There are some other minor exceptions.

AltStyle によって変換されたページ (->オリジナル) /