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

···

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

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

--
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.

Rick summarizes Kent Beck's arguments for direct instance variable access
(in Smalltalk)

I ask whether Kent would have the same position in Ruby, since I felt it
addressed most of his points

Rick asks him, and he does

···

On Thu, Dec 9, 2010 at 8:12 AM, Kedar Mhaswade <kedar.mhaswade@gmail.com>wrote:

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

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