From: webber han Date: 2012-10-26T04:29:29+09:00 Subject: Re: Name/symbol/object type clash? What is happening here? Todd B. wrote in post #1080823: > It's nonsense code, but I'm curious as to what is going on behind the > scenes... > > irb(main):001:0> S = Struct.new(:num) > => S > irb(main):002:0> class S; def change_to n; @num = n; end; end > => nil > irb(main):003:0> s = S.new(3) > # > irb(main):004:0> s.num = 4 > => 4 > irb(main):005:0> s.num > => 4 > irb(main):006:0> s.change_to(5) > => 5 > irb(main):007:0> s.num > => 4 > irb(main):008:0> s.instance_variables > => [:@num] > irb(main):009:0> s.instance_variable_set(:@num, 5) > => 5 > irb(main):010:0> s.num > => 4 > > Same thing happens if I don't define class S, but just define a method > on the instance... def s.change_to n; @num = n; end Ruby is not screwed up! Think about why do you want to use Struct at first place, what Struct gives you? If you think in this direction, then it makes sense that those attribute created when you instantiate a Struct are encapsulated. It is the responsibility of the Struct to handle those data not the class you created using something like Foo = Struct.new. If you really need a instance variable with the same name as one of the attribute from Struct, why on earth would you need Struct at the beginning? High-levelly speaking, Struct gives you something as simple as Hash(since you can do things like obj['attr'] when obj is a struct, and you can iterate!), but less than a real class (you are not able to define a method on struct). The idea is, Struct is awesome if you don't need the power of Class, but you want to bring more domain into your code not just a hash like data structure. Remember, Ruby is awesome and will be awesome forever! Just kidding, it won't... -- Posted via http://www.ruby-forum.com/.