From: "David A. Black" Date: 2008-10-16T00:16:40+09:00 Subject: Re: Lame question about instance variable and attribute --1926193751-1520288824-1224083816=:27697 Content-Type: MULTIPART/MIXED; BOUNDARY="1926193751-1520288824-1224083816=:27697" This message is in MIME format. The first part should be readable text, while the remaining parts are likely unreadable without MIME-aware tools. --1926193751-1520288824-1224083816=:27697 Content-Type: TEXT/PLAIN; charset=X-UNKNOWN; format=flowed Content-Transfer-Encoding: QUOTED-PRINTABLE Hi -- On Thu, 16 Oct 2008, dkmd_nielsen wrote: > On Oct 15, 9:56=A0am, Jes=FAs Gabriel y Gal=E1n > wrote: >> On Wed, Oct 15, 2008 at 4:44 PM, dkmd_nielsen wrote: >>> Assuming an attribute :field is defined, is there a processing >>> difference between using @field and self.field [within the defining >>> class?] =A0Does the ruby interpretter take a different path in yielding >>> the value depending how it is referenced? =A0I haven't notice anything. >>> I'm just curious if the interpretter takes extra steps when yielding >>> self.field. >> >> @field accessed the instance variable directly, while self.field calls >> the method "field" on self. So the paths are completely different: >> >> irb(main):001:0> require 'parse_tree' >> =3D> true >> irb(main):027:0> class B >> irb(main):028:1> attr_reader :b >> irb(main):029:1> def test >> irb(main):030:2> @b >> irb(main):031:2> end >> irb(main):035:1> def test3 >> irb(main):036:2> self.b >> irb(main):037:2> end >> irb(main):038:1> end >> =3D> nil >> irb(main):039:0> ParseTree.new.parse_tree_for_method(B, :test) >> =3D> [:defn, :test, [:scope, [:block, [:args], [:ivar, :@b]]]] >> irb(main):040:0> ParseTree.new.parse_tree_for_method(B, :test3) >> =3D> [:defn, :test3, [:scope, [:block, [:args], [:call, [:self], :b]]]] >> >> Jesus. > > So, in processing that involves many iterations, one should most > definitely use the instance variable reference. Correct? > > When would it be proper to use the self. reference? The self. version is necessary if you do, or think you'll ever do, any kind of override. In other words, if you've got: def name @name.upcase end or whatever, then you'll want to use the method, unless you're doing something even more low-level (like assigning directly to @name). David --=20 Rails training from David A. Black and Ruby Power and Light: Intro to Ruby on Rails January 12-15 Fort Lauderdale, FL Advancing with Rails January 19-22 Fort Lauderdale, FL * * Co-taught with Patrick Ewing! See http://www.rubypal.com for details and updates! --1926193751-1520288824-1224083816=:27697-- --1926193751-1520288824-1224083816=:27697--