makersacademy / ruby-kickstart

Ruby Kickstart
MIT License
39 stars 382 forks source link

Challenge 2:13 - self.var vs @var #343

Closed mbutlerw closed 8 years ago

mbutlerw commented 8 years ago

Anyone who's done/looked at 2.13 able to offer some explanation for the use of self.var over @var in the last question? They both pass tests and so seem to be functionally identical and so I wanted to see if there was a reason why the author used self.var in this case or was it just a stylistic choice.

Here are a few links to explanations of the differences between self.var and @var:

http://stackoverflow.com/questions/12097726/ruby-classes-initialize-self-vs-variable http://stackoverflow.com/questions/1693243/instance-variable-self-vs http://stackoverflow.com/questions/5275749/ruby-should-i-use-self-or

Any thoughts let me know :)

class User
  attr_accessor:username, :blogs

  def initialize(username)
    @username = username
    @blogs = []
  end

  def add_blog(date, text)
    added_blog = Blog.new(date, @username, text)
    blogs << added_blog
    @blogs = blogs.sort_by { |blog| blog.date }.reverse
    added_blog
  end

end

class Blog

  attr_accessor :date, :user, :text

  def initialize(date, user, text)
    @date = date
    @user = user
    @text = text
  end

   def summary
    text.split[0..9].join(' ')
  end

  def entry
    "#{user.username} #{date}\n#{text}"
  end

  def ==(other)
    date   == other.date &&
      user == other.user &&
      text == other.text
  end
end

vs

require 'date'

class User
  attr_accessor :username, :blogs

  def initialize(username)
    self.username = username
    self.blogs    = []
  end

  def add_blog(date, text)
    added_blog = Blog.new(date, self, text)
    blogs << added_blog
    self.blogs = blogs.sort_by { |blog| blog.date }.reverse
    added_blog
  end
end

class Blog
  attr_accessor :date, :user, :text

  def initialize(date, user, text)
    self.date = date
    self.user = user
    self.text = text
  end

  def summary
    text.split[0..9].join(' ')
  end

  def entry
    "#{user.username} #{date}\n#{text}"
  end

  def ==(other)
    date   == other.date &&
      user == other.user &&
      text == other.text
  end
end