From: sto.mar@... Date: 2013-02-02T00:58:59+09:00 Subject: Re: Novice: self, @self.respond_to? and dynamically built methods Am 01.02.2013 16:06, schrieb Steve Tu: > The code I have is now split into separate files that are 'load' or > 'require'd. The argument test file contains: > #----------------------------------------------------------------------- > # F O R M A L A R G U M E N T S > #----------------------------------------------------------------------- > def arguments_test > require 'getoptlong' I like optparse. > > # The parameters can be in any order > STDOUT.puts "Arguments "+ARGV.length.to_s puts uses stdout by default, so you can just use `puts'. > unless ARGV.length >= 1 > `zenity --info --title="Usage ... " --text="Usage: > ./ptutorial.rb -s\"Subject\" -o\"Options\""` > exit > end > > subject = option = '' > # specify the options we accept and initialize > # the option parser > opts = GetoptLong.new( > [ "--subject", "-s", GetoptLong::REQUIRED_ARGUMENT ], > [ "--option", "-o", GetoptLong::OPTIONAL_ARGUMENT ], > ) > # process the parsed options > opts.each do |opt, arg| > case opt > when '--subject' > subject = arg > when '--option' > option = arg > end > end > > STDOUT.puts "(#{self}) - (#{self.to_s}) Supports (#{self.methods})" #{self} sends to_s implicitly, so #{self} and #{self.to_s} are the same > STDOUT.puts "No Class Supports (#{methods})" > > > method = "#{subject.to_s.chomp.downcase}_test" > if self.respond_to?(method) > self.send(method) > else > if self.respond_to?(method,TRUE) > self.send(method,option) > else > `zenity --info --title="Arguments ... " --text="Args: > (#{@self}).... Does Not Support #{method}"` > end > end > > `zenity --info --title="Arguments ... " --text="Args: Subject > (#{subject}) Option (#{option})"` > > end > > > What I now end up with is the 'private' respond_to? test working - which > is one point I don't understand (ie what determines a method's > visibility - I thought it had to be explicitly defined or was assumed as > public?). Seems 'global' methods behave differently, they are private methods of `Object', see http://stackoverflow.com/questions/8799704/are-ruby-imported-methods-always-private > That then lead onto the question re how to determine the > footprint of the method being called, as the code above works if the > method passed accepts a single parameter. If the method accepts o > parameters then the code fails anyway - and hence the question re > whether it is simply then better to just attempt the method call and > trap the errors thrown, rather than trying to see if the method is > supported in the first place. > Am I making any sense at all? You could use an optional argument hash. Still, this approach seems a bit strange to me. Ever thought about defining classes? --