Ordinarily, Ruby methods return the value of the last expression in the method. For setters of the form name=, however, it seems like
Given the following code:
class Foo
attr_reader :bar
def set_bar(v)
@bar = (v + 1)
end
def bar=(v)
@bar = (v + 1)
end
end
If I call either bar= or set_bar(), the value of @bar is the same:
f = Foo.new; f.set_bar(1); f.bar
# => 2
f = Foo.new; f.bar=1; f.bar
# => 2
The setters' return values, however, are different:
f = Foo.new; f.set_bar(1)
# => 2
f = Foo.new; f.bar = 1
# => 1
# note: irb in Ruby 2.7+ suppresses this unless you write (f.bar = 1)
This persists even if I add an explicit return:
class Foo
def bar=(v)
@bar = (v + 1)
return @bar
end
end
f = Foo.new; f.bar = 1
# => 1
This is surprising (I know, Matz has said explicitly that Ruby doesn't follow the principle of least surprise) and it's not obviously documented anywhere. Is it documented? Is there a reason for it?