Ruby Learning

Instance Variables vs Methods

Instance variables (@variable) correspond to private variables in other languages. self.myvariable is actually not a variable, but a call to a method. Similarly, if you write self.myvariable = something, it is actually a call to self.myvariable=(something). This corresponds to properties with getters and setters in other languages.

You can use attr_reader and attr_accessor to automatically define getters and setters for an instance variable. attr_reader will only generate a getter, while attr_accessor generates both.

SO answer

I was confused because I couldn’t see the list of instance variables for a class. But Ruby’s design forces you to keep your instance variables private. The only way you can interact with a class is by its public methods.

So, to understand what a class provides you, look at its methods.

RSpec

To run tests from a specific file:

rake spec SPEC=path/to/spec.rb
Created: February 16, 2016
Last modified: September 28, 2019
Status: in-progress notes
Tags: notes, ruby

comments powered by Disqus