Skip to content

Instantly share code, notes, and snippets.

@franciscoj
Last active May 9, 2016 17:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save franciscoj/39663f5b4b359fd11bbad85d070302a4 to your computer and use it in GitHub Desktop.
Save franciscoj/39663f5b4b359fd11bbad85d070302a4 to your computer and use it in GitHub Desktop.
ivar vs reader

Ruby: ivar vs readers

Spoiler alert: Readers win.

  1. You don't rely on the instance state.
  2. You've better protection againt typos. @ivar might not exist and nothing will fail ivar will complain.
  3. They're easier to mock in specs in case you need to.
  4. They properly wrap the state so that refactors are easier
  5. they can be aliased
  6. they can be alias_method_chained
  7. no kittens will die
  8. you can properly set their accessibility
  9. etc.

When should I use ivars then?

  1. When setting things on the constructor.
  2. When memoizing stuff (and be careful).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment