Hey all,
I''ve been staring at the pickaxe, experimenting, and looking through
some of the Rails API but I can''t put this simple thing together. I
want to create a method that can have zero or more parameters and some
of those are symbols. A very simple example would look something like this:
find(options = {})
if options[:unique]
puts ''Do the unique operation''
else
puts ''Not-unique operation''
end
end
And I want to be able to call this method as "find()" or
"find(:unique)". The above definition works fine if I do
"find()" or
"find(:unique => true)", but it barfs with just :unique.
What''s the
right way to solve this?
Thanks!
- a very tired Jeff
Jeff,
Your method expects the "options" argument to be a Hash.
:unique is a symbol and symbols do not support the [] method.
find(:unique=>true) is a shortcut for find({:unique=>true}).
find(:unique=>true, :another_key=>false) is a shortcut for
find({:unique=>true, :another_key=>false})
Note that only one argument is actually being passed (the Hash).
HTH,
Brian
On 8/21/05, Jeff Casimir <jeff-+RlNNtFrnNmT15sufhRIGw@public.gmane.org>
wrote:
Hey all,
I''ve been staring at the pickaxe, experimenting, and looking through
some of the Rails API but I can''t put this simple thing together. I
want to create a method that can have zero or more parameters and some
of those are symbols. A very simple example would look something like this:
find(options = {})
if options[:unique]
puts ''Do the unique operation''
else
puts ''Not-unique operation''
end
end
And I want to be able to call this method as "find()" or
"find(:unique)". The above definition works fine if I do
"find()" or
"find(:unique => true)", but it barfs with just :unique.
What''s the
right way to solve this?
Thanks!
- a very tired Jeff
_______________________________________________
Rails mailing list
Rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org
http://lists.rubyonrails.org/mailman/listinfo/rails
_______________________________________________
Rails mailing list
Rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org
http://lists.rubyonrails.org/mailman/listinfo/rails
Hello Jeff, Jeff Casimir said the following on 2005-08-22 01:52:> find(options = {}) > if options[:unique] > puts ''Do the unique operation'' > else > puts ''Not-unique operation'' > end > end > > And I want to be able to call this method as "find()" or > "find(:unique)". The above definition works fine if I do "find()" or > "find(:unique => true)", but it barfs with just :unique. What''s the > right way to solve this?What you want should be this: def find(options=nil) if :unique == options # unique operation else # non-unique operation end end As Brian said, you are expecting a Hash, not a single argument. Above is what you want. In fact, this method above can only accept ONE argument. If you need more than one, you should do this instead: def find(*options) if options.include?(:unique) # unique operation else # non-unique operation end end Hope that helps ! François