attr_reader
is a "getter method". In other words, it allows us to declare that a data attribute will be publicly read-able.
When you save a data attribute on an instance of a class, that data can't be viewed from outside of the class by default. With attr_reader
set, we can access that attribute from anywhere.
Here's an example using the "name" field from your question.
class DocumentIdentifier
def initialize(folder, name)
@folder = folder
@name = name
end
end
first_example = DocumentIdentifier.new(nil, 'test')
first_example.name
This will give an error:
Traceback (most recent call last):
4: from /Users/ibell/.rvm/rubies/ruby-2.6.5/bin/irb:23:in `<main>'
3: from /Users/ibell/.rvm/rubies/ruby-2.6.5/bin/irb:23:in `load'
2: from /Users/ibell/.rvm/rubies/ruby-2.6.5/lib/ruby/gems/2.6.0/gems/irb-1.0.0/exe/irb:11:in `<top (required)>'
1: from (irb):9
NoMethodError (undefined method `name' for #<DocumentIdentifier:0x00007fe0160956e8 @folder=2, @name="l">)
Now, if you add the attr_accessor
, the same code will work.
class DocumentIdentifier
attr_reader :name
def initialize(folder, name)
@folder = folder
@name = name
end
end
second_example = DocumentIdentifier.new(nil, 'test')
second_example.name
This will give you the string "test" back.
Just as we need to read data, we might also want to write it. attr_writer
works similarly to attr_reader
, but it allows us to "set" data.
class DocumentIdentifier
attr_writer :name
def initialize(folder, name)
@folder = folder
@name = name
end
end
second_example = DocumentIdentifier.new(nil, 'test')
second_example.name = 'we can change this text'
second_example.name
This will give you back: 'we can change this text'
Lastly, attr_accessor
is a shortcut for when you want attr_reader
and attr_writer
on the same attribute.