Convetion regarding accessing attributes (from within instancemethods).

K

Kedar Mhaswade

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
 
A

Alex Young

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
 
J

Josh Cheek

[Note: parts of this message were removed to make it a legal post.]

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top