Raj Sahae
2/26/2007 3:11:00 AM
Pedro Del Gallego wrote:
> I've a question about the :parameter notation.
> I want to write a method that can hold several optional paramters
>
> add_book :title=>"El quijote", :author=> "Miguel de Cervantes"
> add_book :title=>"El quijote", :author=> "Miguel de Cervantes",
> :tag=>"novel"
> add_book :title=>"El quijote"
To have a method with optional variables, assign them to nil in the
declaration. If they aren't included in the method call, they will be
set to nil.
def add_book(title, author = nil, tag = nil)
> but the interpreter said : ./bibliom.rb:7:in `add_book': undefined
> method `title' for {:title=>"El quijote", :author=>"Miguel de
> Cervantes"}:Hash (NoMethodError)
It gives you this error because you are using attr_writer, which is
equivalent to a def attr= method. In order to simply return a value,
you should use attr_reader, or in case you want both, attr_accessor.
I think what you want is along the lines of:
class Book
attr_accessor :title, :author, :tag
def initialize(title, author = nil, tag = nil)
self.title = title
self.author = author
self.tag = tag
end
def add_book
puts "title: #{self.title} -- Author: #{self.author}"
end
end