Significance of State

Learn specifications of state in Ruby language.

We'll cover the following

How to access State variable

State is kept in the instance variable @state ( we can name it however we want), and by default, there is no standard way to access this variable from outside. There is no limitation about how a state should look. . We might want to use 10 instance variables and implement sophisticated business logic inside our class, but the API—in our case, these two methods, open and how_are_you—remains the same.

Similar to a real car, we might want to play music inside. However, unless our API implements it, nobody will ever notice we have music playing inside. This principle is known as encapsulation.

Suppose that, when driving down the road, we meet a hitchhiker. The hitchhiker is shy, so they don’t want to open the car door. They would like to ask us, “How are you?” but before, they need to ensure that the door is open. In other words, we want others to read our state and read our instance variable or variables. How would we do that?

The easiest way is to add a method with a meaningful name that returns the state. We could add aaa, but let’s call it the state:

class Car
  def initialize
    @state = :closed
  end

  # new method goes below
  def state
    @state
  end

  def open
    @state = :open
  end

  def how_are_you
    puts "My state is #{@state}"
  end
end

Get hands-on with 1200+ tech skills courses.