From: Austin Ziegler Date: 2006-01-27T12:13:53+09:00 Subject: Re: Pass References To Methods As Arguments? On 26/01/06, wegzumir wrote: > Hey all. I am trying to determine the Ruby syntax for passing a > reference to a method. I want to actually pass the reference itself as > an argument to another method. There is no way to do that directly in Ruby. > Consider the following simplified Perl example. It features two > subroutine functions and another subroutine that is capable of calling > any subroutine passed to it as a reference. > > sub print_unix_line { > print shift, "\n" > } > > sub print_windows_line { > print shift, "\015\012"; > } > > sub call_a_routine { > my ($routine, $argument) = @_; > $routine->($argument); > } > > &call_a_routine(\&print_unix_line, 'Hello, unix World!'); > &call_a_routine(\&print_windows_line, 'Hello, Windows World!'); Your example really isn't a good one, but: 1. print_unix_line = lambda { |arg| print arg + "\n" } print_wind_line = lambda { |arg| print arg + "\015\012" } def call_a_routine(routine, argument) routine[argument] # or: routine.call(argument) end call_a_routine(print_unix_line, "Hello, unix.") call_a_routine(print_wind_line, "Hello, Windows.") 2. class Routines def print_unix_line(arg) print arg + "\n" end def print_wind_line(arg) print arg + "\015\012" end end def call_a_routine(routine, argument) @@routine ||= Routines.new @@routine.__send__(routine, argument) end call_a_routine(:print_unix_line, "Hello, unix.") call_a_routine(:print_wind_line, "Hello, Windows.") As far as the poorness of the example you have, you don't need to do anything special with Ruby to print properly: puts "Hello Ruby, World" What exactly are you really trying to do? -austin -- Austin Ziegler * halostatue@gmail.com * Alternate: austin@halostatue.ca