Hi all,
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"
When you use this kind of argument for a method it is encapulated into an
anonymous hash. It's like writing
add_book( { :title=>"El quijote", :author=> "Miguel de Cervantes",
:tag=>"novel" } )
and i had write the add_book mehod like this :
class Book
attr_writer :title, :author
end
def add_book (book )
puts "title : #{book.title} -- Author : #{book.author}"
end
You've added the attr_writer, but you may want to make it into an
attr_accessor
so that you have both reader and writer
Your add_book should look something like, can't give it to you exactly.
sorri no ruby at work
def add_book( book )
title = book[:title] || nil
author = book[:author] || nil
puts "title : #{title} -- Author : #{author}"
end
Since book is an Hash, you need to access it as book[:title]. You need to
assign the book[:title] given to the book object to its own title, the one
you made the accessor for.
I must say though that I don't quite understand how you can add_book to a
book. I would expect to see this as part of an initialize method instead.
That way you would write
book = Book.new( :title => 'bla', :author => 'author' )
But that's just me.
but the interpreter said : ./bibliom.rb:7:in `add_book': undefined
method `title' for {:title=>"El quijote", :author=>"Miguel de
Cervantes"}:Hash (NoMethodError)
I also try to put a hash object in the incoming parameter, like that :
def add_book (book=) .... end
What this does is sets the local variable book, inside the add_book method
to an empty array by default. ie if there is no parameter passed then you
can rely on it being an empty array.
···
On 2/26/07, Pedro Del Gallego <pedro.delgallego@gmail.com> wrote: