From: Josh Cheek Date: 2011-10-05T21:59:03+09:00 Subject: Re: Local vs method vs instance --bcaec517ac92a0b62204ae8cc588 Content-Type: text/plain; charset=ISO-8859-1 On Wed, Oct 5, 2011 at 4:00 AM, Brian Candler wrote: > Darryl Pierce wrote in post #1025016: > > On 10/04/2011 11:42 AM, Chris Hulan wrote: > >> but doing it this way makes the x public readable, so should only be > >> used if that is needed > >> I'd stick with using @x > > > > AH! That's what I missing, and what he meant by "the method". Okay. The > > OP though didn't have the attr_accessor on the fields, though, that I > > remember. > > This was implied by the use of 'other.x'. If you can write 'other.x' > then that object must have a method called 'x'. Since we're talking > about adding two objects of the same class, this means self also has a > method 'x', and you can call this just using 'x'. > > Now, if you don't want to have accessors on your Point class, then it > gets a little bit messy to tinker with the internals of the other > object: e.g. > > @x + other.instance_variable_get(:@x) > > or > > @x + other.instance_eval { @x } > > I think you could also use a 'protected' accessor method, but I've never > found the need to use those. > > -- > Posted via http://www.ruby-forum.com/. > > For that, you could use protected: class UselessPoint def initialize(x, y) @x, @y = x, y end def +(point) UselessPoint.new point.x+x, point.y+y end protected attr_reader :x, :y end p1 = UselessPoint.new 1, 2 p2 = UselessPoint.new 3, 4 p1 + p2 # => # p1.x # => # ~> -:19:in `
': protected method `x' called for # (NoMethodError) --bcaec517ac92a0b62204ae8cc588--