From: Colin Bartlett Date: 2010-09-03T05:12:36+09:00 Subject: Re: selecting a variable number of individual items --0016e6d7ea6944d6da048f4c6ffd Content-Type: text/plain; charset=ISO-8859-1 On Thu, Sep 2, 2010 at 8:38 PM, Joe Pizzanley wrote: > Colin Bartlett wrote: > > I'm a bit hesitant to suggest this because you've been studying Ruby a > > long time, > you're assuming that I've gotten good at it. It's still confusing to me > in many spots. > > > and because I don't think I understand sufficiently what you want to do. > the second half of your sentence is proof that I haven't gotten good at it. > Well, there is a difference between not knowing what you want to do, and knowing what you want to do but not be able to explain what you want to do! :) > > However your solution gave me enough to go on. I can push the arguments > into an array and then iterate through selecting whatever is in the array. > thanks for extending help Colin! Much appreciated. > No trouble: I wasn't sure what level to pitch any explanation at, and the examples were aimed at what I thought you wanted to do - it seems that I wasn't all that far off? The following is a very simplified explanation of Ruby method arguments, targetted at want you want to do. There's a longer (not quite up-to-date - Ruby 1.9 allows more method argument options) explanation here: http://ruby-doc.org/docs/ProgrammingRuby/html/tut_methods.html class VarArgsExample # example showing compulsory arguments, default arguments, # and variable length arguments def example_meth( arg0, arg1, arg2 = 222, arg3 = 333, *args ) puts "0=#{arg0.inspect}, 1=#{arg1.inspect}," \ " 2=#{arg2.inspect}, 3=#{arg3.inspect};" \ " var len args= #{args.inspect};" "return value" end end obj = VarArgsExample.new obj.example_meth( ) rescue (p $!) #=> # obj.example_meth( 'apple' ) rescue (p $!) #=> # obj.example_meth( 'apple', 'fig' ) #=> 0="apple", 1="fig", 2=222, 3=333; var len args=[] obj.example_meth( 'apple', 'fig', 'lemon' ) #=> 0="apple", 1="fig", 2="lemon", 3=333; var len args=[] obj.example_meth( 'apple', 'fig', 'lemon', 'grape' ) #=> 0="apple", 1="fig", 2="lemon", 3="grape"; var len args=[] obj.example_meth( 'apple', 'fig', 'lemon', 'grape', 'cherry' ) #=> 0="apple", 1="fig", 2="lemon", 3="grape"; var len args=["cherry"] obj.example_meth( 'apple', 'fig', 'lemon', 'grape', 'cherry', 'blossom' ) #=> 0="apple", 1="fig", 2="lemon", 3="grape"; var len args=["cherry", "blossom"] For what you want do you can just do: def select_values( *args ) # array args holds all the arguments passed to this method; # and if you want to trap if no arguments were passed then if args.size == 0 then raise "select_values must have at least one argument" end end --0016e6d7ea6944d6da048f4c6ffd--