Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

attr vs attr_accessor

Tags:

In Ruby there are four different getter and setter methods for instance variables, attr, attr_reader, attr_writer, and attr_accessor. The question is, is in Ruby attr :dilithium, the same as attr_reader :dilithium, and identical to attr_accessor :dilithium if an additional parameter true is passed? That is to say is

class Enterprise   attr :dilithium, true 

identical to

class Enterprise   attr_accessor :dilithium 

Are the two functions attr and attr_accessor more or less redundant?

like image 367
0x4a6f4672 Avatar asked Dec 19 '12 17:12

0x4a6f4672


People also ask

What is attr_accessor?

attr_accessor is a shortcut method when you need both attr_reader and attr_writer . Since both reading and writing data are common, the idiomatic method attr_accessor is quite useful.

What does ATTR reader do?

Summary. attr_reader and attr_writer in Ruby allow us to access and modify instance variables using the . notation by creating getter and setter methods automatically. These methods allow us to access instance variables from outside the scope of the class definition.

What is Attr_accessible?

What is attr_accessible? In Ruby on Rails, attr_accessible allows you to specify which attributes of a model can be altered via mass-assignment (most notably by update_attributes(attrs) and new(attrs) ). Any attribute names you pass as parameters will be alterable via mass-assignment, and all others won't be.

What are attributes in Ruby?

Attributes are key-value pairs containing information that determines the properties of an event or transaction.


1 Answers

One difference is that attr_accessor and friends are clearer, and the optional boolean argument to attr is now deprecated. Other than that, and the fact that attr has no documentation, there's no real difference.

like image 161
Linuxios Avatar answered Jan 06 '23 18:01

Linuxios