Attr reader/writer confused


#1



https://www.codecademy.com/en/courses/ruby-beginner-en-zfe3o/0/5?curriculum_id=5059f8619189a5000201fbcb


I'm confused about attr read/writer. First of all it's confusing because the whole code that attr brings was not discussed at all before, it didnt even seem neccersary to have.

Does it need to be there to be accesable? Does "def name" let me read it from outside of the class? If i remove the name method it still lets me access it. And for job i have no clue at all whats it doing. I know that the writing part but that also went well without any code in previous excersise.

So i'm talking here about the actual code that replaces attr. Please help me out:)


class Person
  def initialize(name, job)
    @name = name
    @job = job
  end
  
  def name
    @name
  end
  
  def job=(new_job)
    @job = new_job
  end
end

newperson = Person.new("Jim", "Baker")
newperson.name  
#  "Jim"
=================================================
class Person
  def initialize(name, job)
    @name = name
    @job = job
  end
  
  def job=(new_job)
    @job = new_job
  end
end

newperson = Person.new("Jim", "Baker")
newperson.name  
#  "Jim"


#2

Actually commenting it out or otherwise removing it does make it inaccessible, it's just that ruby lets you split up a class into more than one definition, and codecademy doesn't restart the interpreter between runs (you would need to refresh page)

example:

class Test
  def hello
    'Hello'
  end
end

class Test
  def there
    ' there!'
  end
end

my_test = Test.new
puts my_test.hello + my_test.there  # Hello there!

#3

thank you so much for your quick reply.

Could you or someone still explain to me the "def job =(new_job)" and why does name not need a write method like that? Name and Job both set a value right?


#4

That's a setter method


#5

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