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

Another way to understand it is to figure out what error code it eliminates by having attr_accessor.

Example:

class BankAccount    
  def initialize( account_owner )
    @owner = account_owner
    @balance = 0
  end

  def deposit( amount )
    @balance = @balance + amount
  end

  def withdraw( amount )
    @balance = @balance - amount
  end
end

The following methods are available:

$ bankie = BankAccout.new("Iggy")
$ bankie 
$ bankie.deposit(100)
$ bankie.withdraw(5)

The following methods throws error:

$ bankie.owner     #undefined method `owner'... 
$ bankie.balance   #undefined method `balance'...

owner and balance are not, technically, a method, but an attribute. BankAccount class does not have def owner and def balance. If it does, then you can use the two commands below. But those two methods aren't there. However, you can access attributes as if you'd access a method via attr_accessor!! Hence the word attr_accessor. Attribute. Accessor. It accesses attributes like you would access a method.

Adding attr_accessor :balance, :owner allows you to read and write balance and owner "method". Now you can use the last 2 methods.

$ bankie.balance
$ bankie.owner
查看更多
步步皆殇っ
3楼-- · 2018-12-31 03:17

The main functionality of attr_accessor over the other ones is the capability of accessing data from other files.
So you usually would have attr_reader or attr_writer but the good news is that Ruby lets you combine these two together with attr_accessor. I think of it as my to go method because it is more well rounded or versatile. Also, peep in mind that in Rails, this is eliminated because it does it for you in the back end. So in other words: you are better off using attr_acessor over the other two because you don't have to worry about being to specific, the accessor covers it all. I know this is more of a general explanation but it helped me as a beginner.

Hope this helped!

查看更多
怪性笑人.
4楼-- · 2018-12-31 03:20

attr_accessor is (as @pst stated) just a method. What it does is create more methods for you.

So this code here:

class Foo
  attr_accessor :bar
end

is equivalent to this code:

class Foo
  def bar
    @bar
  end
  def bar=( new_value )
    @bar = new_value
  end
end

You can write this sort of method yourself in Ruby:

class Module
  def var( method_name )
    inst_variable_name = "@#{method_name}".to_sym
    define_method method_name do
      instance_variable_get inst_variable_name
    end
    define_method "#{method_name}=" do |new_value|
      instance_variable_set inst_variable_name, new_value
    end
  end
end

class Foo
  var :bar
end

f = Foo.new
p f.bar     #=> nil
f.bar = 42
p f.bar     #=> 42
查看更多
孤独总比滥情好
5楼-- · 2018-12-31 03:21

Simple Explanation Without Any Code

Most of the above answers use code. This explanation attempts to answer it without using any, via an analogy/story:

Outside parties cannot access internal CIA secrets

  • Let's imagine a really secret place: the CIA. Nobody knows what's happening in the CIA apart from the people inside the CIA. In other words, external people cannot access any information in the CIA. But because it's no good having an organisation that is completely secret, certain information is made available to the outside world - only things that the CIA wants everyone to know about of course: e.g. the Director of the CIA, how environmentally friendly this department is compared to all other government departments etc. Other information: e.g. who are its covert operatives in Iraq or Afghanistan - these types of things will probably remain a secret for the next 150 years.

  • If you're outside the CIA you can only access the information that it has made available to the public. Or to use CIA parlance you can only access information that is "cleared".

  • The information that the CIA wants to make available to the general public outside the CIA are called: attributes.

The meaning of read and write attributes:

  • In the case of the CIA, most attributes are "read only". This means if you are a party external to the CIA, you can ask: "who is the director of the CIA?" and you will get a straight answer. But what you cannot do with "read only" attributes is to make changes changes in the CIA. e.g. you cannot make a phone call and suddenly decide that you want Kim Kardashian to be the Director, or that you want Paris Hilton to be the Commander in Chief.

  • If the attributes gave you "write" access, then you could make changes if you want to, even if you were outside. Otherwise, the only thing you can do is read.

    In other words accessors allow you to make inquiries, or to make changes, to organisations that otherwise do not let external people in, depending on whether the accessors are read or write accessors.

Objects inside a class can easily access each other

  • On the other hand, if you were already inside the CIA, then you could easily call up your CIA operative in Kabul because this information is easily accessible given you are already inside. But if you're outside the CIA, you simply will not be given access: you will not be able to know who they are (read access), and you will not be able to change their mission (write access).

Exact same thing with classes and your ability to access variables, properties and methods within them. HTH! Any questions, please ask and I hope i can clarify.

查看更多
临风纵饮
6楼-- · 2018-12-31 03:26

Defines a named attribute for this module, where the name is symbol.id2name, creating an instance variable (@name) and a corresponding access method to read it. Also creates a method called name= to set the attribute.

module Mod
  attr_accessor(:one, :two)
end
Mod.instance_methods.sort   #=> [:one, :one=, :two, :two=]
查看更多
孤独总比滥情好
7楼-- · 2018-12-31 03:27

To summarize an attribute accessor aka attr_accessor gives you two free methods.

Like in Java they get called getters and setters.

Many answers have shown good examples so I'm just going to be brief.

#the_attribute

and

#the_attribute=

In the old ruby docs a hash tag # means a method. It could also include a class name prefix... MyClass#my_method

查看更多
登录 后发表回答