Example of State

Learn how the state is used and its advantages in Ruby with the help of an example.

We'll cover the following...

Now, it’s more or less clear what the state is. But how is it used in practice? What’s the advantage of having a state? Why would we keep the state inside of an object, and why do we need to encapsulate?

As we already know, an object is a living organism. So, it’s better to combine multiple variables that affect the flow of a program under one hood and avoid using them separately.

Robot example

Imagine we have a robot that walks on the ground, and we’re observing the scene from the top. The robot starts moving at a certain point and can move left, right, up, and down by any number of steps.

At first glance, it looks like we could avoid using any classes here. ...