Question

I do understand that Ruby supports short-hand style of calling methods i.e: 1.+(2) is same as 1+2 (and I still think if it related to my situation), but I got really confused why attr_accessor methods are neither duplicate (well, they should not be, as writer differs with = in its name) nor they differ with anything (except writer needs an argument) while accessing them outside active object.

My question is included in this code (in the second comment)

class Test
  def initialize(number)
    @number = number
  end
  def number
    @number
  end
  def number=(n)
    @number = n
  end
end

t = Test.new(12)

puts t.number # => 12
t.number = 13 # Why does it do what t.number=(13) should do
puts t.number # => 13

I wonder why t.number = 13 works, when it points to a method which should only return a number and moreover how does it set a new value when t.number=(13) is not called instead.

Was it helpful?

Solution

t.number = 13 is just a shorthand for t.number=(13), they are effectively the same statement in Ruby.

attr_accessor :b creates the equivalent of the following two methods:

def b
  @b
end
def b=(new_val)
  @b = new_val
end

So in your code example, you could replace the two methods #number and #number= with attr_accessor :number

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top