Now you’re probably wondering, why don’t we just make the User->first_name property public? That way we can set it with $user->first_name = 'Amy' and skip all of that Setter/Getter nonsense.

Well you could do it that way, but let’s say we need to perform a transformation on that data. For example, what happens if our user makes a mistake and forgets to capatilize their own name during registration?

Those familiar with Laravel’s Eloquent ORM will be scratching their heads at this example. Under the hood Eloquent is doing something similar by storing the model’s data as an array under $_attributes and using some clever PHP magic methods to check for specially named setter methods.

It’s a little complex to show here. The classic Getter/Setter method is much easier to understand.

Ruby’s Setters/Getters

You may have noticed to get that functionality we had to do quite a bit of typing. That’s normal for statically defined languages like PHP and Java. It’s verbose and kind of ceremonious.

Ruby offers a special shortcut to create setters and getters for your classes. Let’s start with the way we’d normally create a new class based on what we know about static languages:

Yup, you’re seeing that right. There’s a big ole = right in the method name. Alongside of the fact it accepts an argument, it’s exactly the same name as our getter.

It’s threw me for a tiff for a long time. Don’t expect it to be or feel natural at first. But here’s the class in use just like we did in the PHP implementation:

user=User.newuser.first_name('Amy')putsuser.first_name=>'Amy'

Using Ruby Shorthand to Generate Setters and Getters

Now manually typing getters and setters for Ruby’s classes are lot less legwork (or should I say fingerwork) typing than it’s PHP cousin. But we have another special treat that’s built into the Ruby language.

It’s natural for Ruby to have shortcuts for building out OOP functionality since everything is an object.

Ruby offers 3 more specialized keywords in classes to generate getters, setters or both at the same time.

Let’s generate the setters and getters seperately. Now this will be logically equivalent to our User class in former examples:

Not only do you have the shortcut methods of attr_reader and attr_writer but you have a third method that covers both: attr_accessor.

This means we can reduce our User class to 3 lines of code:

classUserattr_accessor:first_nameend

This will give us the same exactly functionality, but with a huge cost savings in terms of typing. Reducing this type of boilerplate is huge for your productivity and ultimately let’s you solve problems rather that typing or relying on a heavy IDE to constantly create boilerplate code.