From: RichardOnRails Date: 2010-12-23T23:10:16+09:00 Subject: Re: How to DRY code to prompt for parameters On Dec 22, 11:55 pm, Josh Cheek wrote: > [Note:  parts of this message were removed to make it a legal post.] > > On Wed, Dec 22, 2010 at 10:10 PM, RichardOnRails < > > > > RichardDummyMailbox58...@uscomputergurus.com> wrote: > > I pasted code to prompt for a couple of parameter-values at > >http://www.pastie.org/1399710. > > > Running this code under SciTE produces, for example: > > Getting parms > >        Account Number: 123 > >        Report  Period: 456 > > Showing parms > >        @acct_num = 123 > >        @acct_period = 456 > > > It is excessively verbose because I couldn't figure out how to use > > meta-language to specify the parameter target names.  That led me to > > using case statements to accept input values and then populate the > > instance variables. > > > Can anyone suggest how I can use the instance variables as targets in > > lieu of the case statements?  BTW, I want to get this working with > > meta-programming.  I don't want to use some other approach, such as a > > plug-in for getting arguments. > > > Thanks in Advance, > > Richard > > I think you are looking for instance_variable_set and instance_variable_get. > I don't really understand all the decisions you made, such as the array of > hashes, to me that implies you want ordered hashes, but are on 1.8 (If you > are in Rails, you have ActiveSupport loaded, and it provides an OrderedHash > class that you can use) since they are ordered in 1.9. To get around that, I > just made it an Array of Structs. Anyway, hopefully you can get out of this > whatever you're trying to do. > > class X > >   def initialize >     param = Struct.new :human_readable , :ivar >     @rpt_parms = [ >       param.new( "Account Number" , "@acct_num"    ), >       param.new( "Report  Period" , "@acct_period" ), >     ] >   end > >   def get_parms >     @rpt_parms.each do |param| >       print "\t#{param.human_readable}: " >       instance_variable_set( param.ivar , gets.to_i ) # don't need to chomp, > to_i will ignore the newline >     end >   end > >   def show_parms >     @rpt_parms.each do |param| >       value = instance_variable_get(param.ivar) >       puts "\t#{param.human_readable} = #{value}" >     end >   end > >   def run >     puts "Getting parms" >     get_parms >     puts "Showing parms" >     show_parms >   end > > end > > X.new.run > I think you are looking for instance_variable_set and instance_variable_get. That's also exactly the thing I needed! Excellent!! > To get around that, I just made it an Array of Structs. Another responder did what I really wanted but was too stupid to do is: @parms = { "Account Name" => :acct_name, "Account Number" => :acct_num } # etc. Thanks very much for your insights. Best wishes, Richard