From: sto.mar@... Date: 2013-02-01T22:38:11+09:00 Subject: Re: Novice: self, @self.respond_to? and dynamically built methods Am 01.02.2013 12:36, schrieb Steve Tu: > I have been plodding through a Ruby tutorial and came across the > 'require' > and 'load' methods(?). Prior to that, all of the tutorial examples I > played with had been bolted into one file. I had added in a 'zenity' > based menu option to drive the selection of the tutorial subjects. > Now I have split each of the tutorial subjects into separate files that > get 'loaded' or 'required'. The 'main' section is then just a call to > the zenity menu driver, and calls to the respective methods. > > All works fine...apart from... > > I had an old tutorial module that looked at the passing of arguments > into Ruby from the command line. This example did little more than split > the arguments into the argument type and value and then displayed them. > I thought it would be nice then to revisit this and make the argument > type the name of a tutorial 'method' and the argument value any value > required by that tutorial method. > > This seemed relatively straight forward, so I could now call my Ruby > module as: > ./ptutorial.rb -s"HASHES" -o"1" > > From my driver menu, I could then select the argument tutorial - and it > would split the two arguments into a variable containing a method name > (by downcasing and appending _test to the -s argument) and option > variable. > > Now, to stop a call to a non existent method, I wanted to see if the > built method variable existed as a method. > > What I thought I could then do, was to see if 'self' responded to the > method by using: > if self.respond_to?(method) > > but it seems that 'self' does not respond to that method - although if I > call self.send(method, option) it appears to work fine (even though if I > look at the methods that self/@self supports via the methods method, > none of my 'local' tutorial methods appear). > > I thought that it may be down to use of 'self' as opposed to '@self' but > both fail on the respond_to?, and seem to process the method ok on the > send. > > What I want is to dynamically build a method name, then see if the > object (in this case 'self' or the current module) supports that method > and if so to then execute that method with any optional arguments. To me, this does not sound like a use case for metaprogramming. Why don't you use a method that takes the section as an argument? But to your question: I assume you are talking about 'global' methods? If so, I cannot reproduce your problem: 1.9.3p374 :001 > def test_method; puts 'test'; end => nil 1.9.3p374 :002 > self.methods.include?(:test_method) => true 1.9.3p374 :003 > test_method test => nil 1.9.3p374 :004 > self.send(:test_method) test => nil 1.9.3p374 :005 > self.respond_to?(:test_method) => true --