Working with class fields in Ruby.

OOP in this Ruby of yours is quite different from OOP in our proletarian php =). For example, let's take something as trivial as class fields. Despite the fact that methods are encapsulated, fields are not. (In other words, access modifiers cannot be applied to fields). All fields are protected. This means, on the one hand, we are forced to write code "conceptually": getters, setters, and other unseemly things, on the other hand, we need to write a bunch of uninformative code (getters/setters). Fortunately, in Ruby there are means to automate this: the keywords attr_accessor, attr_reader, attr_writer. The first keyword is both a getter and a setter, the next two, as evident from the names, are a getter and a setter respectively. Here is an example of their usage:

class Foo
  attr_accessor :id,
                 :name,
                 :email

end

foo = Foo.new #setter foo.id = 1

#getter a = foo.id

I hope you remember the peculiarities of Ruby and know that the last line is a method call, not an assignment to the object field, as it may seem at first glance.

In case of inheritance, the fields simply stack up: if we create another class Goo:

class Goo < Foo

end

then the following code makes sense:
goo = Goo.new
#setter 
goo.id = 1 

#getter a = goo.id

Naturally, it is convenient to use this if the getter/setter does not contain any additional logic. However, if there is such logic, we cannot avoid directly declaring the getters/setters:
class Foo
  def id=(val)
    #some logic
    @id = val
  end

def id #some logic @id end end

Note that class variables start with the @@ symbol, and instance variables start with @ It now becomes clear why foo.id = 1 is a method call, not an assignment: since parentheses are not necessary for method calls, it is equivalent to writing foo.id = 1, or foo.id=(1) (but you should never do that!).