Convetion regarding accessing attributes (from within instance methods)

I observed that once I have defined attr_accessor for an attribute of a
class, I can access it with or without an ‘@’ leading the name of
attribute (i.e. both [1] and [2] work correctly).

I find accessing it without leading ‘@’ more natural (when there are no
conflicts with local variables).

What is the Ruby community convention in this regard?

Regards,
Kedar

[1]
#!/usr/bin/env ruby
class Car
attr_accessor :color
def initialize(color)
@color = color
end

def print_color
puts @color
end
end

c = Car.new(“blue”)
c.print_color

[2]
#!/usr/bin/env ruby
class Car
attr_accessor :color
def initialize(color)
@color = color
end

def print_color
puts color
end
end

c = Car.new(“blue”)
c.print_color

I prefer to use @, for the following reason:

class A
attr_accessor :foo

def do_thing
  @foo = "this"
  foo = "that"

  puts @foo # -> "this", not "that", which might be a surprise
end

end

A.new.do_thing


Alex

On Thu, Dec 9, 2010 at 8:12 AM, Kedar M.
[email protected]wrote:

Kedar
puts @color
def initialize(color)


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

I prefer the latter (2). Also, in the latter “@color = color” can be
rewritten to use the setter with “self.color = color”

There are prominent people who prefer the former (1), though. To do them
justice, here is a previous exchange on the topic:

Here I explain why I prefer using the accessor to access the instance
variable.
http://www.ruby-forum.com/topic/211544#919532

Rick summarizes Kent Beck’s arguments for direct instance variable
access
(in Smalltalk)
http://www.ruby-forum.com/topic/211544#919648

I ask whether Kent would have the same position in Ruby, since I felt it
addressed most of his points
http://www.ruby-forum.com/topic/211544#919728

Rick asks him, and he does
http://www.ruby-forum.com/topic/211544#920235