I have a class
@title = title.capitalize
b = Book.new
"title": wrong number of arguments
attr_accessor :title does is create wrapper methods, identical to
def title() and
def title=(value). It's just a syntactic sugar method generation. You can then set the value with:
b.title = "Whatever"
and access with:
If you just wanted a reader or a writer, you could use
attr_reader :title or
attr_writer :title separately.
If you want to make your own reader/writer methods manually, all the above do is create:
def title @title end def title=(value) @title = value end
You can't have two methods with the same name and different arity in Ruby, so when you define your own method (as in your question), you're overwriting the reader method with your writer. That leaves you with two ways to set and no way to read.
You could use
attr_reader and a custom writer:
def title=(value) @title = value.capitalize end
You can always name the method anything you want, like
def capitalize_and_set_title(value). It might be more clear than the magic of
attr_accessor and operator overloading.