2

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?

1 Answer 1

3

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.

2
  • 2
    One minor difference is that assignment expressions return the assigned value, regardless of the assignment method’s return value, allowing for chained assignments.
    – Stefan
    Commented Jul 10 at 8:00
  • ...and in the case of method invocation, regardless of whether or not assignment actually occurs. Commented Jul 10 at 13:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.