the_prole the_prole - 5 days ago 5
Ruby Question

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

I have a class

Book
with an instance variable
title
and a method
title


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


I create a book object

b = Book.new


And then I set the title

b.title("inferno")


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?

Thanks

Answer

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:

b.title

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.

Comments