What is attr_accessor in Ruby?

2018-12-31 02:20发布

I am having a hard time understanding attr_accessor in Ruby. Can someone explain this to me?

标签: ruby
18条回答
后来的你喜欢了谁
2楼-- · 2018-12-31 03:00

I think part of what confuses new Rubyists/programmers (like myself) is:

"Why can't I just tell the instance it has any given attribute (e.g., name) and give that attribute a value all in one swoop?"

A little more generalized, but this is how it clicked for me:

Given:

class Person
end

We haven't defined Person as something that can have a name or any other attributes for that matter.

So if we then:

baby = Person.new

...and try to give them a name...

baby.name = "Ruth"

We get an error because, in Rubyland, a Person class of object is not something that is associated with or capable of having a "name" ... yet!

BUT we can use any of the given methods (see previous answers) as a way to say, "An instance of a Person class (baby) can now have an attribute called 'name', therefore we not only have a syntactical way of getting and setting that name, but it makes sense for us to do so."

Again, hitting this question from a slightly different and more general angle, but I hope this helps the next instance of class Person who finds their way to this thread.

查看更多
琉璃瓶的回忆
3楼-- · 2018-12-31 03:04

It is just a method that defines getter and setter methods for instance variables. An example implementation would be:

def self.attr_accessor(*names)
  names.each do |name|
    define_method(name) {instance_variable_get("@#{name}")} # This is the getter
    define_method("#{name}=") {|arg| instance_variable_set("@#{name}", arg)} # This is the setter
  end
end
查看更多
永恒的永恒
4楼-- · 2018-12-31 03:05

attr_accessor is very simple:

attr_accessor :foo

is a shortcut for:

def foo=(val)
  @foo = val
end

def foo
  @foo
end

it is nothing more than a getter/setter for an object

查看更多
旧时光的记忆
5楼-- · 2018-12-31 03:05

Basically they fake publicly accessible data attributes, which Ruby doesn't have.

查看更多
流年柔荑漫光年
6楼-- · 2018-12-31 03:07

Simply put it will define a setter and getter for the class.

Note that

attr_reader :v is equivalant to 
def v
  @v
end

attr_writer :v is equivalant to
def v=(value)
  @v=value
end

So

attr_accessor :v which means 
attr_reader :v; attr_writer :v 

are equivalant to define a setter and getter for the class.

查看更多
梦该遗忘
7楼-- · 2018-12-31 03:07

Simply attr-accessor creates the getter and setter methods for the specified attributes

查看更多
登录 后发表回答