From: Eric Hodel Date: 2006-01-27T12:15:30+09:00 Subject: Re: Pass References To Methods As Arguments? On Jan 26, 2006, at 5:41 PM, 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. > > 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" > } def print_unix(line) print "#{line}\n" end > sub print_windows_line { > print shift, "\015\012"; > } def print_windows(line) print "#{line}\r\n" end > sub call_a_routine { > my ($routine, $argument) = @_; > $routine->($argument); > } def call_a_routine(args) yield args end > &call_a_routine(\&print_unix_line, 'Hello, unix World!'); > &call_a_routine(\&print_windows_line, 'Hello, Windows World!'); call_a_routine('hello, unix world!') { |line| print_unix line } call_a_routine('hello, windows world') { |line| print_windows line } > The "\&" prefixed parts are references to subroutines. I have > tried to > recreate this logic in Ruby using Proc blocks, but I can't get it > to work > properly. Any suggestions? You can turn a Method into a block argument with &: call_a_routine 'text', &method(:print_unix) call_a_routine 'text', &method(:print_windows) but don't do that, its ugly. Use blocks. -- Eric Hodel - drbrain@segment7.net - http://segment7.net This implementation is HODEL-HASH-9600 compliant http://trackmap.robotcoop.com