I don't get it


#1

class Person
attr_reader :name
attr_writer :job
def initialize(name, job)
@name = name
@job = job
end
end

I really am lost… like how and what does attr_reader do, how do u input new variables? I am posting after a lot of confusion… I think I should spend more time reading things and practicing…


#2

An attr_reader is getter specially designed to replace the typical method for returning an attribute’s value.

def name
    @name 
end

An attr_writer is a setter specially designed to replace a method for setting an attribute’s value.

def job(newJob)
    @job = newJob
end

With the getter, we simply write,

john = Person.new('John', 'programmer')

puts john.name     # John
john.job = 'analyst'

One assumes we will have an attr_reader for job as well,

attr_reader :name, :job

puts john.job    # analyst

There is one more detail relating to both read and write, attr_accessor

attr_accessor :job

This will install both a getter and a setter on the job attribute so we don’t need to give it a reader or a writer.

Relating to the colon, it is part of the identifier and in Ruby it is known as a symbol.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.