From: Robert Klemme Date: 2005-08-10T21:06:10+09:00 Subject: Re: passing a method Wybo Dekker wrote: > Patrick Gundlach and Devin Mullans wrote: > > > @t = '' > > def bye > > @t << 'bye' > > end > > def hello > > @t << 'hello' > > end > > def doit(f) > > send f > > end > > doit(:hello) > > doit(:bye) > > doit(:hello) > > puts @t > > That's exactly what I needed. Thanks! > > As for daniel's question: > > > Why do you want to do this? > > and > > > This is a rather poor example, since the above three lines > > could just as well be written like this: > > > hello > > bye > > hello > > Of course, that's because an exmaple should be short. > My actual code is an initializer for my scripts. I find myself all the > time re-inserting, in many scripts, code to test if executables are > available, code to read rc-files, to handle options, and more. I want > to put most of that stuff in a module which now contains an init > method using the above suggestion (for the last argument): > > # program initializer: > # 1. check if all needed executables (in _needed_) are available > # 2. set the defaults (values of _defaults_) for > # option- and rc-variables (keys of _defaults_) > # 3. read the standard rc-files > # 4. handle the options, as defined in the _optionproc_ method > # 5. if @rc appears to be defined, read it as an rc-file > > def init(needed,defaults,option_handler) > @rcfiles = [] # collect names for a report in case @verbose is true > > # set defaults: > defaults.each do |k,v| > eval("@#{k} = #{v || 'nil'}") > end > > # check if all needed executables (in _needed_) are available > check_execs(needed) > > # run all standard rc-files > read_rc_files(defaults.keys) > > # handle options > send option_handler > > # in case a --rc option was used, read its argument as an rc-file: > read_rc_file(@rc,defaults.keys) > > # if the --verbose option was used, report rc-files read: > if @verbose > if @rcfiles.size > 0 > puts "These rc files were read:",@rcfiles.join("\n") > else > puts "No rc files were read" > end > end > end IMHO a superior solution would be to use a block instead of argument option_handler. AFAICS you have only one such callback and that's exactly what blocks are for. If you want access to the current instance you can use instance_eval: def init(needed,defaults,&option_handler) .... # handle options instance_eval &option_handler .... end Also, for setting instance variables, this idiom is better (because it avoids evil eval and you don't need special handling of nil): defaults.each {|k,v| instance_variable_set("@#{k}", v)} Kind regards robert