Ruby: Variable initialization within classes - ruby

Having some trouble when it comes to initializing variables within a class (instance variables etc.) and I was wondering if anybody could clarify the proper syntax for me.
Sample code:
Class Pets
attr_accessor :name
def initialize(name)
#name=name
end
def name=(name)
#name = name
#I believe this is where I change #name instance variable
end
#in this space I could create more <methods> for Class.new.<method>
end
My question is do I need to have attr_accessor as well as def initialize and def name=?
In addition, if I have multiple attr_accessors do I need to add them as arguments to def initialize, e.g.:
Class Pets
attr_accessor :name :age :color
def initialize(name, age, color)
#name = name
#age = age
#color = color
#and if this is the case do I need methods for each (name= age= color= etc.)
end
One last thing:
If someone could confirm or deny my thought process on the name= age= and color= type of methods within the classes. Am I correct in thinking method= is necessary to change the instance variable? I am a bit unsure about what the method= is for and why I cannot change the instance variable within initialize.

attr_accessor :symbol do the same as attr_writer :symbol and attr_reader :symbol, i.e. it creates both reader (def symbol; #symbol; end) and writer (def symbol=(value); #symbol = value; end).
Initialize is a method called every time new instance of the class is being created. It is not the same as new method as some classes may have its own custom factory methods. You don't need to define your initialize method, only problem is that then symbol reader would return nil, as the local variable would not been set.
In ruby everything is a method. In case of objects, object.attr = value is just a short for object.attr=(value) where attr= is just another method. (Similarly << operator is defined as a method on Array class, attr_accessor is a method defined on class "Class").

To piggy back on what what said earlier, recall that if you want your attributes to be accessible outside your class (you want to write over the attribute value or you want to read it) you will need to use the attr_accessor (or attr_writer or attr_reader).
If I had a class like ...
class Calendar
attr_reader :event_name, :all_events
def initialize
#event_name = event_name
#all_events = []
end
def create_event(event_name)
puts "#{event_name} has been added to your calendar."
#all_events << event_name
p #all_events
end
def see_all_events
puts "Here are your events --"
#all_events.each {|event| puts "- #{event}"}
end
end
my_calendar=Calendar.new
my_calendar.create_event("interview")
my_calendar.see_all_events
my_calendar.all_events
I can read all my events either with the method see_all_events or by calling all_events on my class Calendar object. If for some reason I did not want a see_all_events method but instead only wanted it to be seen by calling all_events on my object I can only do this because of attr_reader.
Basically the point here is to remember exactly how you want your users to interact with your object attributes. If it needs to be private and only accessed via methods then you should be weary of using attr_accessor or attr_writer or attr_reader (depending on the situation).

Related

What is the difference between an instance method used to rename an object and a setter method?

If I want to rename my jedi object below, why would I create an instance method named rename that uses the setter method name=? Why not just use the setter method `name=' directly?
Why do this:
class Skywalker
attr_accessor :name
def initialize(name)
#name = name
end
def rename(new_name)
self.name = new_name
end
end
jedi = Skywalker.new('Anakin')
puts jedi.name
jedi.rename('Luke')
puts jedi.name
When you could just do this:
class Skywalker
attr_accessor :name
def initialize(name)
#name = name
end
end
jedi = Skywalker.new('Anakin')
puts jedi.name
jedi.name = 'Luke'
puts jedi.name
Both code snippets above do the same thing, so I'm wondering if there is a situation where it would be useful to have the instance method rename in addition to the setter method name=. Because to me it looks like they are redundant.
#rename hides the implementation details. You expose a clean and explicit interface - an object can be renamed, but the caller doesn't have to care how it's done. I would recommend to use attr_reader :name instead of attr_accessor :name to avoid exposing the setter.
If you expose just #name= you let the caller to change object internals. It may cause the future changes harder (e.g. if you move name to a separate object).

Accessing an instance variable within the `initialize` method

Given this basic class in Ruby:
class TestClass
def initialize(name)
#name = name
end
end
How do I then access the instance variable name directly from within the initialize method without creating a getter function? is this even possible? (i.e. using dot notation) or does the initialize method cease to exist once a class is instantiated, hence the need to define a getter method?
I think what I'm trying to ask is initialize a class or instance method?
The "getter method" is defined so that you can use the variable from outside the class:
class TestClass
attr_reader :name
def initialize(name)
#name = name
end
end
# TestClass.new('Ben').name # => 'Ben'
If you don't need to access it from outside the class, you can just use #name:
class TestClass
def initialize(name)
#name = name
end
def greet
puts "Hello, %s" % #name
end
end
# TestClass.new('Ben').greet # outputs: Hello, Ben
You can use the #name inside initialize:
class TestClass
def initialize(name)
#name = name
puts "Name backwards: %s" % #name.reverse
end
end
# TestClass.new('Ben') # outputs neB
Initialize is a special method, when you define initialize instance method, it is automatically marked private. The class method new calls it after creating an instance of your class.
Nothing stops you from calling private methods from inside the class:
class TestClass
def initialize(name)
#name = name
puts "Name is now %s" % #name
end
def flip_name
initialize(#name.reverse)
end
end
# t = TestClass.new('Ben') # outputs "Name is now Ben"
# t.flip_name # outputs "Name is now neB"
# t.instance_variable_get(:#name) # => 'neB'
The flip_name method that calls initialize works just fine, but of course this is quite unconventional and almost never used, because it does not make much sense.
It's possible to call private methods from outside the class using send:
# t.send(:initialize, 'Bill') # outputs "Name is now Bill"
# t.instance_variable_get(:#name) # => 'Bill'
Without send, you get NoMethodError:
> t.initialize('Jack')
NoMethodError: private method `initialize' called for #<TestClass:0x00007fa2df8e4570>
Ruby 1.9 beta releases changed send to act like public_send does today, allowing access to only public methods and there was going to be funccall for calling private methods if you really want to, for unit testing purposes for example. I think it caused too much compatibility issues and the change was reverted.
So in conclusion, yes, you can call initialize again and it does not cease to exist, but it is almost never done because it makes very little sense. To access instance variables from inside the class, you use # notation like #name, to access them from outside of the class, you define a getter.
Yes, there is a way. But it's not a traditional one. It's more like querying the object to know
TestClass.new("foo").instance_variable_get(:#name)
=> "foo"
The initialize method does not "cease to exsist". It's executed, that's it. What your method do, in your case, is that the variable is set.

Understanding Ruby Setters

If I create a class like this:
class Player
def initialize(position, name)
#position = position
#name = name
end
end
Isn't that setting the name to an instance variable? if so, why would I need to write a setter like this
class Player
def initialize(position, name)
#position = position
#name = name
end
def name=(name)
#name = name
end
end
Basically when is it necessary to write getters in a class?
Getters and setters job is to provide you a quick implementation of read and write of instance variables that you define in your constructor:
class Player
attr_accessor :name, :position
def initialize(position, name)
#position = position
#name = name
end
end
you can also user attr_reader(for getters) and attr_writer(for setters) specifically for these variables.
Above code: attr_accessor :name, :position gives you: #name, #position, #name=, and #position= methods for instance of Player class.
However, they're not going to give you validation or a customized logic for getters/setters.
For example: you might want to show a player's full name or do not wish your code to accept a 0 or negative position, in such a case you'd have to write getter and setter yourself:
class Player
def initialize(first_name, last_name, position)
#first_name = first_name
#last_name = last_name
#position = position
end
# validation for updating position using setter of position
def position=(new_position)
raise "invalid position: #{new_position}" if new_position <= 0
#position = new_position
end
# customized getter for name method
def name
"#{#first_name} #{#last_name}"
end
end
If you do not require customization as stated above then using attr_* method for these variables makes more sense.
initialize sets attributes during the initialization of a new object.
keeper = Player.new('goalkeeper','Shilton').
What if you want to update an attribute of keeper after initialzation? Well you'll need to use your ordinary setter method:
def name=(name)
#name = name
end
like so:
keeper.name = 'Banks'
If you don't have a setter method defined for Player instances, then you can't do this. Similarly for getter methods. Also be aware you can refactor your code by using attr_accessor like so:
class Player
attr_accessor :name, :position
def initialize(position, name)
#position = position
#name = name
end
end
Getters/setters, also known as "accessors", are accessible outside the class, instance variables are not. If you want things to be able to read or change #name from outside the class, you to define accessors for it.
Additionally accessor methods allow you to perform a certain amount of sanity checking or mutate incoming/outgoing values, and otherwise protect the internal state of your objects.

Intermingling attr_accessor and an initialize method in one class

I see code like:
class Person
def initialize(name)
#name = name
end
end
I understand this allows me to do things like person = Person.new and to use #name elsewhere in my class like other methods. Then, I saw code like:
class Person
attr_accessor :name
end
...
person = Person.new
person.name = "David"
I'm just at a loss with these two methods mesh. What are the particular uses of def initialize(name)? I suppose attr_accessor allows me to read and write. That implies they are two separate methods. Yes? Want clarifications on def initialize and attr_accessor and how they mesh.
initialize and attr_accessor have nothing to do with each other. attr_accessor :name creates a couple of methods:
def name
#name
end
def name=(val)
#name = val
end
If you want to set name upon object creation, you can do it in the initializer:
def initialize(name)
#name = name
# or
# self.name = name
end
But you don't have to do that. You can set name later, after creation.
p = Person.new
p.name = "David"
puts p.name # >> "David"
Here is the answer you are looking for Classes and methods. Read it carefully.
Here is a good documentation from the link:
Classes and methods
Now we are ready to create our very own Address class. Let's start simple. Let's start with an address that only contains the "street" field.
This is how you define a class:
class Address
def initialize(street)
#street = street
end
end
Let's go through this:
The class keyword defines a class.
By defining a method inside this class, we are associating it with this class.
The initialize method is what actually constructs the data structure. Every class must contain an initialize method.
#street is an object variable. Similar to the keys of a hash. The # sign distinguishes #street as an object variable. Every time you create an object of the class Address, this object will contain a #street variable.
Let's use this class to create an address object.
address = Addres.new("23 St George St.")
That's it. address is now an object of the class Address
Reading the data in an object
Suppose that we want to read the data in the address object. To do this, we need to write a method that returns this data:
class Address
def initialize(street)
#street = street
end
# Just return #street
def street
#street
end
end
Now the method Address#street lets you read the street of the address. In irb:
>> address.street
=> "23 St George St."
A property of an object, which is visible outside, is called an attribute. In this case, street is is an attribute. In particular, it is a readable attribute. Because this kind of attribute is very common, Ruby offers you a shortcut through the attr_reader keyword:
class Address
attr_reader :street
def initialize(street)
#street = street
end
end
Changing the data in an object
We can also define a method to change the data in an object.
class Address
attr_reader :street
def initialize(street)
#street = street
end
def street=(street)
#street = street
end
end
Ruby is pretty smart in its use of the street= method:
address.street = "45 Main St."
Notice that you can put spaces betten street and =. Now that we can change the address data, we can simplify the initialize method, and have it simply default the street to the empty string "".
class Address
attr_reader :street
def initialize
#street = ""
end
def street=(street)
#street = street
end
end
address = Address.new
address.street = "23 St George St."
This might not seem like much of a simplification, but when we add the city, state and zip fields, and more methods this will make the class definition a bit simpler.
Now, street is also a writable attribute. As before, you can declare it as such with attr_writer:
class Address
attr_reader :street
attr_writer :street
def initialize
#street = ""
end
end
Accessing data
Very often, you have attributes that are both readable and writable attributes. Ruby lets you lump these together with attr_accessor. I guess these would be called "accessible attributes", but I have never seen them be called that.
class Address
attr_accessor :street
def initialize
#street = ""
end
end
With this knowledge, it is now easy to define the entire addressbook structure. As it turns out, attr_accessor and friends all accept multiple arguments.
class Address
attr_accessor :street, :city, :state, :zip
def initialize
#street = #city = #state = #zip = ""
end
end
I think you consider initialize as a constructor. To be precise, it is not. The default constructor is the new method on the class, and initialize is called by that method. If you do not define initialize, you can still create an object with new because initialize is not the constructor itself. In that case, the default initialize does nothing. If you do define initialize, then that is called right after the object creation.
The statement #foo = ... and attr_accessor :foo are different. The former assigns a value to the instance variable #foo, whereas the latter lets you access #foo via methods foo and foo=. Without the latter, you can still access #foo by directly describing so.
Unlike C++,Java instance variables in Ruby are private by default(partially as they can be accessed by using a.instance_variable_get :#x)
eg:
class Dda
def initialize task
#task = task
#done = false
end
end
item = Dda.new "Jogging" # This would call the initializer and task = Jogging would
be set for item
item.task # would give error as their is no function named task to access the instance
variable.
Although we have set the value to item but we won't be able to do anything with it as instace variables are private in ruby.
code for getter:
def task
#task
end
#for getter
def task=task
#task = task
end
Using getter would ensure that item.task returns it's value
And using setter gives us the flexibility to provide values to instance variables at any time.

What is attr_accessor in Ruby?

I am having a hard time understanding attr_accessor in Ruby.
Can someone explain this to me?
Let's say you have a class Person.
class Person
end
person = Person.new
person.name # => no method error
Obviously we never defined method name. Let's do that.
class Person
def name
#name # simply returning an instance variable #name
end
end
person = Person.new
person.name # => nil
person.name = "Dennis" # => no method error
Aha, we can read the name, but that doesn't mean we can assign the name. Those are two different methods. The former is called reader and latter is called writer. We didn't create the writer yet so let's do that.
class Person
def name
#name
end
def name=(str)
#name = str
end
end
person = Person.new
person.name = 'Dennis'
person.name # => "Dennis"
Awesome. Now we can write and read instance variable #name using reader and writer methods. Except, this is done so frequently, why waste time writing these methods every time? We can do it easier.
class Person
attr_reader :name
attr_writer :name
end
Even this can get repetitive. When you want both reader and writer just use accessor!
class Person
attr_accessor :name
end
person = Person.new
person.name = "Dennis"
person.name # => "Dennis"
Works the same way! And guess what: the instance variable #name in our person object will be set just like when we did it manually, so you can use it in other methods.
class Person
attr_accessor :name
def greeting
"Hello #{#name}"
end
end
person = Person.new
person.name = "Dennis"
person.greeting # => "Hello Dennis"
That's it. In order to understand how attr_reader, attr_writer, and attr_accessor methods actually generate methods for you, read other answers, books, ruby docs.
attr_accessor is just a method. (The link should provide more insight with how it works - look at the pairs of methods generated, and a tutorial should show you how to use it.)
The trick is that class is not a definition in Ruby (it is "just a definition" in languages like C++ and Java), but it is an expression that evaluates. It is during this evaluation when the attr_accessor method is invoked which in turn modifies the current class - remember the implicit receiver: self.attr_accessor, where self is the "open" class object at this point.
The need for attr_accessor and friends, is, well:
Ruby, like Smalltalk, does not allow instance variables to be accessed outside of methods1 for that object. That is, instance variables cannot be accessed in the x.y form as is common in say, Java or even Python. In Ruby y is always taken as a message to send (or "method to call"). Thus the attr_* methods create wrappers which proxy the instance #variable access through dynamically created methods.
Boilerplate sucks
Hope this clarifies some of the little details. Happy coding.
1 This isn't strictly true and there are some "techniques" around this, but there is no syntax support for "public instance variable" access.
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
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
Basically they fake publicly accessible data attributes, which Ruby doesn't have.
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
If you are familiar with OOP concept, You must familiar with getter and setter method.
attr_accessor does the same in Ruby.
Getter and Setter in General Way
class Person
def name
#name
end
def name=(str)
#name = str
end
end
person = Person.new
person.name = 'Eshaan'
person.name # => "Eshaan"
Setter Method
def name=(val)
#name = val
end
Getter method
def name
#name
end
Getter and Setter method in Ruby
class Person
attr_accessor :name
end
person = Person.new
person.name = "Eshaan"
person.name # => "Eshaan"
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.
I faced this problem as well and wrote a somewhat lengthy answer to this question. There are some great answers on this already, but anyone looking for more clarification, I hope my answer can help
Initialize Method
Initialize allows you to set data to an instance of an object upon creation of the instance rather than having to set them on a separate line in your code each time you create a new instance of the class.
class Person
def initialize(name)
#name = name
end
def greeting
"Hello #{#name}"
end
end
person = Person.new("Denis")
puts person.greeting
In the code above we are setting the name “Denis” using the initialize method by passing Dennis through the parameter in Initialize. If we wanted to set the name without the initialize method we could do so like this:
class Person
attr_accessor :name
# def initialize(name)
# #name = name
# end
def greeting
"Hello #{name}"
end
end
person = Person.new
person.name = "Dennis"
puts person.greeting
In the code above, we set the name by calling on the attr_accessor setter method using person.name, rather than setting the values upon initialization of the object.
Both “methods” of doing this work, but initialize saves us time and lines of code.
This is the only job of initialize. You cannot call on initialize as a method. To actually get the values of an instance object you need to use getters and setters (attr_reader (get), attr_writer(set), and attr_accessor(both)). See below for more detail on those.
Getters, Setters (attr_reader, attr_writer, attr_accessor)
Getters, attr_reader: The entire purpose of a getter is to return the value of a particular instance variable. Visit the sample code below for a breakdown on this.
class Item
def initialize(item_name, quantity)
#item_name = item_name
#quantity = quantity
end
def item_name
#item_name
end
def quantity
#quantity
end
end
example = Item.new("TV",2)
puts example.item_name
puts example.quantity
In the code above you are calling the methods “item_name” and “quantity” on the instance of Item “example”. The “puts example.item_name” and “example.quantity” will return (or “get”) the value for the parameters that were passed into the “example” and display them to the screen.
Luckily in Ruby there is an inherent method that allows us to write this code more succinctly; the attr_reader method. See the code below;
class Item
attr_reader :item_name, :quantity
def initialize(item_name, quantity)
#item_name = item_name
#quantity = quantity
end
end
item = Item.new("TV",2)
puts item.item_name
puts item.quantity
This syntax works exactly the same way, only it saves us six lines of code. Imagine if you had 5 more state attributable to the Item class? The code would get long quickly.
Setters, attr_writer: What crossed me up at first with setter methods is that in my eyes it seemed to perform an identical function to the initialize method. Below I explain the difference based on my understanding;
As stated before, the initialize method allows you to set the values for an instance of an object upon object creation.
But what if you wanted to set the values later, after the instance was created, or change them after they have been initialized? This would be a scenario where you would use a setter method. THAT IS THE DIFFERENCE. You don’t have to “set” a particular state when you are using the attr_writer method initially.
The code below is an example of using a setter method to declare the value item_name for this instance of the Item class. Notice that we continue to use the getter method attr_reader so that we can get the values and print them to the screen, just in case you want to test the code on your own.
class Item
attr_reader :item_name
def item_name=(str)
#item_name = (str)
end
end
The code below is an example of using attr_writer to once again shorten our code and save us time.
class Item
attr_reader :item_name
attr_writer :item_name
end
item = Item.new
puts item.item_name = "TV"
The code below is a reiteration of the initialize example above of where we are using initialize to set the objects value of item_name upon creation.
class Item
attr_reader :item_name
def initialize(item_name)
#item_name = item_name
end
end
item = Item.new("TV")
puts item.item_name
attr_accessor: Performs the functions of both attr_reader and attr_writer, saving you one more line of code.
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.
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.
Simply attr-accessor creates the getter and setter methods for the specified attributes
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
Despite the large number of existing answers, none of them seems to me to explain the actual mechanism involved here. It's metaprogramming; it takes advantage of the following two facts:
You can modify a module / class on the fly
A module / class declaration is itself executable code
Okay, so imagine the following:
class Nameable
def self.named(whatvalue)
define_method :name do whatvalue end
end
end
We are declaring a class method named which, when called with a value, creates an instance method called name which returns that value. That is the metaprogramming part.
Now we'll subclass that class:
class Dog < Nameable
named "Fido"
end
What on earth did we just do? Well, in the class declaration, executable code executes with reference to the class. So the bare word named is actually a call to the class method named, which we inherited from Nameable; and we are passing the string "Fido" as the argument.
And what does the class method named do? It creates an instance method called name, which returns that value. So now, behind the scenes, Dog has a method that looks like this:
def name
"Fido"
end
Don't believe me? Then watch this little move:
puts Dog.new.name #=> Fido
Why did I tell you all that? Because what I just did with named for Nameable is almost exactly what attr_accessor does for Module. When you say attr_accessor you are calling a class method (inherited from Module) that creates instance methods. In particular, it creates a getter and setter method for the instance property whose name you provide as argument, so that you don't have to write those getter and setter methods yourself.
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=]
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
I am new to ruby and had to just deal with understanding the following weirdness. Might help out someone else in the future. In the end it is as was mentioned above, where 2 functions (def myvar, def myvar=) both get implicitly for accessing #myvar, but these methods can be overridden by local declarations.
class Foo
attr_accessor 'myvar'
def initialize
#myvar = "A"
myvar = "B"
puts #myvar # A
puts myvar # B - myvar declared above overrides myvar method
end
def test
puts #myvar # A
puts myvar # A - coming from myvar accessor
myvar = "C" # local myvar overrides accessor
puts #myvar # A
puts myvar # C
send "myvar=", "E" # not running "myvar =", but instead calls setter for #myvar
puts #myvar # E
puts myvar # C
end
end
Attributes and accessor methods
Attributes are class components that can be accessed from outside the object. They are known as properties in many other programming languages. Their values are accessible by using the "dot notation", as in object_name.attribute_name. Unlike Python and a few other languages, Ruby does not allow instance variables to be accessed directly from outside the object.
class Car
def initialize
#wheels = 4 # This is an instance variable
end
end
c = Car.new
c.wheels # Output: NoMethodError: undefined method `wheels' for #<Car:0x00000000d43500>
In the above example, c is an instance (object) of the Car class. We tried unsuccessfully to read the value of the wheels instance variable from outside the object. What happened is that Ruby attempted to call a method named wheels within the c object, but no such method was defined. In short, object_name.attribute_name tries to call a method named attribute_name within the object. To access the value of the wheels variable from the outside, we need to implement an instance method by that name, which will return the value of that variable when called. That's called an accessor method. In the general programming context, the usual way to access an instance variable from outside the object is to implement accessor methods, also known as getter and setter methods. A getter allows the value of a variable defined within a class to be read from the outside and a setter allows it to be written from the outside.
In the following example, we have added getter and setter methods to the Car class to access the wheels variable from outside the object. This is not the "Ruby way" of defining getters and setters; it serves only to illustrate what getter and setter methods do.
class Car
def wheels # getter method
#wheels
end
def wheels=(val) # setter method
#wheels = val
end
end
f = Car.new
f.wheels = 4 # The setter method was invoked
f.wheels # The getter method was invoked
# Output: => 4
The above example works and similar code is commonly used to create getter and setter methods in other languages. However, Ruby provides a simpler way to do this: three built-in methods called attr_reader, attr_writer and attr_acessor. The attr_reader method makes an instance variable readable from the outside, attr_writer makes it writeable, and attr_acessor makes it readable and writeable.
The above example can be rewritten like this.
class Car
attr_accessor :wheels
end
f = Car.new
f.wheels = 4
f.wheels # Output: => 4
In the above example, the wheels attribute will be readable and writable from outside the object. If instead of attr_accessor, we used attr_reader, it would be read-only. If we used attr_writer, it would be write-only. Those three methods are not getters and setters in themselves but, when called, they create getter and setter methods for us. They are methods that dynamically (programmatically) generate other methods; that's called metaprogramming.
The first (longer) example, which does not employ Ruby's built-in methods, should only be used when additional code is required in the getter and setter methods. For instance, a setter method may need to validate data or do some calculation before assigning a value to an instance variable.
It is possible to access (read and write) instance variables from outside the object, by using the instance_variable_get and instance_variable_set built-in methods. However, this is rarely justifiable and usually a bad idea, as bypassing encapsulation tends to wreak all sorts of havoc.
Hmmm. Lots of good answers. Here is my few cents on it.
attr_accessor is a simple method that helps us in cleaning(DRY-ing) up the repeating getter and setter methods.
So that we can focus more on writing business logic and not worry about the setters and getters.
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!

Resources