0

I am confused of when to add 'self.'. Does self.title call a function named 'title' or 'title' is simply a instance variable?

class Movie < ActiveRecord::Base
  # reminder: database columns are id, title, rating, release_date
  # method 1:
  def title_with_year_1
  "#{self.title} - #{self.release_date.year}"
  end

  # method 2:
  def title_with_year_2
  "#{title} - #{release_date.year}"
  end

  # method 3:
  def title_with_year_3
  "#{@title} - #{@release_date.year}"
  end
end

And if I add attr_accessor :title, release_date to it ,would the method 3 work as intended?

glt
  • 11
  • 2
  • http://stackoverflow.com/questions/4639271/directly-accessing-an-instance-variable-vs-using-an-accessor-method some info here – Eyeslandic Jan 06 '17 at 16:27
  • And don't worry if you're confused, it is a constant source of confusion for me even after 10 years of Ruby. – Eyeslandic Jan 06 '17 at 16:28
  • I think I have figured out something. One more question, if I add `attr_accessor :title, release_date` to it ,would the method 3 work as intended? – glt Jan 06 '17 at 16:46
  • No, because when you add `attr_accessor` it would generate setter and getter methods for that attributes that override the original getter and setter mehods that are generated by ActiveRecord. – spickermann Jan 06 '17 at 17:04
  • Thanks for your nice help. – glt Jan 06 '17 at 17:53

0 Answers0