From: Ken Bloom Date: 2007-02-27T00:10:06+09:00 Subject: Re: Methods and :parameters On Mon, 26 Feb 2007 10:57:59 +0900, Pedro Del Gallego wrote: > 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" > > 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 > > 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 > > My question is how can i wirte a method with several optional parameter > and then acces they inside of the mehotd ? def add_book (book ) puts "title : #{book[:title]} -- Author : #{book[:author]}" end When using the named parameter idiom, all of the named parameters are lumped together into a single hash which is passed as the last parameter. There's no point in defining the Book class -- it won't be used by this idiom. If you want to access the parameters as members, then you can construct an OpenStruct inside the method, like so require 'ostruct' def add_book book book=OpenStruct.new(book) puts "title : #{book.title} -- Author : #{book.author}" end but that's most likely overkill. -- Ken Bloom. PhD candidate. Linguistic Cognition Laboratory. Department of Computer Science. Illinois Institute of Technology. http://www.iit.edu/~kbloom1/