the_prole the_prole - 1 year ago 53
Ruby Question

How to print attribute accessor value when attribute accessor has same name as method

I have a class

with an instance variable
and a method

class Book
attr_accessor :title
def title(title)
@title = title.capitalize

I create a book object

b =

And then I set the title


Now when I try to print the title field variable value

p b.title

Ruby thinks I'm trying to call the method

"title": wrong number of arguments

Any idea how to print the field variable value?


Answer Source

All 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

def title=(value)
  @title = value

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download