Re: Why is top-level an object rather than just Object?



Thomas Sawyer wrote in post #956401:
On Oct 22, 3:36pm, Intransition <transf...@xxxxxxxxx> wrote:
It should not be. In fact, I think it is a mistake for main to
module Main

for a minute your objections, but concentrating instead on replicating
end
x = Y.new(10)
y = Y.new(20)

puts x #=> "10"
puts y #=> "20"

@a = 30

puts x #=> "30"
puts y #=> "30"

My bad, that's not quite right. The @a would be at the class level,
so:

class X
def self.to_s
@a ||= 10
end
end

class Y
def self.to_s
@a ||= 20
end
end

puts X #=> "10"
puts Y #=> "20"

@a = 30

puts X #=> "30"
puts Y #=> "30"

@Thomas:

Dude, instance variables are not inherited in this way. Every object
gets its OWN instance variable table, including the Object class. There
is no confusion and no mix up, behold:

class X
def self.to_a
@a || = 10
end
end

class Y
def self.to_a
@a ||= 20
end
end

X #=> 10
Y #=> 20

class Object
@a = 30
end

X #=> 10
Y #=> 20

@a #=> 30

Having the instance variables on the Object class would NOT cause any of
the conflicts you guys are talking about :)

@Thomas, @Robert,

Have you guys checked out 'wrapped loads' ? In my edit to my previous
answer I wrote this:

"Have you checked out the 'load' function in Ruby? it has a feature
called 'wrapped loads' that loads the file into an anonymous module.
This means the loaded file cannot affect the global namespace and any
constants including classes and modules are trapped within the
anonymous module. Just call load with a second argument of anything
other than nil."

John

--
Posted via http://www.ruby-forum.com/.

.



Relevant Pages

  • Re: Dynamically changing class methods
    ... Im making an application that loads and uses the methods of a class ... methods using 'def'. ... require 'dynaload' ...
    (comp.lang.ruby)
  • Re: Suggestions for common/global data in app (cli)
    ... The main menu loads, then other classes available in other files ... def initialize ... I had a copy of the code lying around, ... in the container which you don't access don't get created. ...
    (comp.lang.ruby)
  • Re: "Meggahurtz"
    ... Sorry still unclear, was that def duckies_uk@xxxxxxxxxxxxx, i`m worried because the spambots might pick up duckies_uk@xxxxxxxxxxxxx email address and send loads of crap to duckies_uk@xxxxxxxxxxxxx which will make me lose so much sleep knowing duckies_uk@xxxxxxxxxxxxx was getting loads of junk ...
    (uk.telecom.mobile)