Taken this class as a example:
class House
def initialize(color, size)
@color = color
@size = size
end
def color
@color
end
# Is the = part of the syntax or a convention?
def color=(color)
@color = color
end
end
Is the equal '=' at the end of the setter-method a convention, like the '!' or the '?'? Or does is add functionality?
It is “only” a convention, like ending methods returning a boolean with ?
or adding a !
when there is a less dangerous counterpart method.
You could define the setter method with (Java style)
def set_color(color)
@color = color
end
or even using Unicode
def 🎨(color)
@color = color
end
and it wouldn't make any difference at runtime.
Btw in this example, you could also use
attr_writer :color
See attr_writer
, attr_reader
, and attr_accessor
.