Devin Mullins
9/5/2006 2:00:00 PM
gaurav bagga wrote:
> thanks all for the help
>
> 5 =MyNum.new
>
> i wanted to do this just to have fun as most of the classes in ruby are
> open
> String,Array... to be extended was trying same with Fixnum...... if
> possible....
Ah. Well, you can touch Fixnum, but there's not much you can do with 5.
irb(main):001:0> class Fixnum; def squared; self * self end end
=> nil
irb(main):002:0> puts (1..10).map {|i| i.squared}.join(', ')
1, 4, 9, 16, 25, 36, 49, 64, 81, 100
=> nil
irb(main):003:0> def 5.foo; end
SyntaxError: compile error
(irb):3: parse error, unexpected tINTEGER
def 5.foo; end
^
(irb):3: parse error, unexpected kEND, expecting $
from (irb):3
irb(main):004:0> a = 5
=> 5
irb(main):005:0> def a.foo; end
TypeError: can't define singleton method "foo" for Fixnum
from (irb):5
irb(main):006:0> 5.instance_eval { @bar = 'quux' }
=> "quux"
irb(main):007:0> 5.instance_variable_get :@bar
=> "quux"
irb(main):008:0> 6.instance_eval { @bar }
=> nil
irb(main):009:0> "sdgsdg".object_id
=> 23037396
irb(main):010:0> "sdgsdg".object_id
=> 21070012
irb(main):011:0> "sdgsdg".object_id
=> 21055864
irb(main):012:0> 5.object_id
=> 11
irb(main):013:0> 5.object_id
=> 11
irb(main):014:0> 5.object_id
=> 11
In the last bit, notice how the String object_ids are all divisible by
four. That's Ruby's cue that they're Real Objects, and object_id >> 2 is
the start of the memory location they've been alloc'ed (IIRC). That 5
has an object_id not divisible by four is Ruby's cue that it's not a
real object -- actually, that it's odd is Ruby's cue that its a Fixnum.
irb(main):015:0> (-1000..1000).all? {|i| i == i.object_id >> 1}
=> true
See, with Fixnums, no object is actually alloc'ed and pointed to. The
pointer *is* an encoding of the number. Hence, no singleton methods for you.
Odd that you can define instance variables, but I'm sure if I bothered
to read the Ruby source, it'd make perfect sense.
Devin