From: Stefan Lang Date: 2005-07-29T22:01:52+09:00 Subject: Re: [newbie] make local var visible On Friday 29 July 2005 13:55, "Pe�a, Botp" wrote: > #IMHO not necessary. Ruby already has what you want. You > #want a closure. > # > #foo=["a","b","c"] > # > #mfoo = lambda do > #� � foo.each do |f| > #� � � � p f > #� � end > #end > # > #mfoo.call > # > > Yes, Stefan. Thank you. Lambda and proc have been suggested. > But i still want something cleaner. I hope you can understand what I mean, English is not my native language: It seems that you want to access some state from within the method. In Perl, this state would be the variables in the enclosing scope, since every sub in Perl is essentielly a closure (AFAIK). In Ruby, the state which a method has access to is self, with its instance variables. So for your purpose, use instance variables. And to make it even cleaner, try to wrap it up in a class. > Can we make something like proc but do it inside out? We do not > adjust the methods but the vars, that is. > > I am just trying to bridge the gap of bash/perl/sh and ruby. You can fake Perl's subs with Ruby's lambdas, but that would be far from idiomatic. Let's translate a little Perl script to Ruby: % cat count_files.pl my @dirs = @ARGV; @dirs = (".") unless @dirs; my $file_count = 0; sub count_files_in_dir { my $dir = shift; opendir(DH, $dir); my @files = grep { -f "$dir/$_" } readdir(DH); closedir(DH); $file_count += scalar(@files); } for my $dir (@dirs) { count_files_in_dir($dir); } print "Number of files: $file_count\n"; ########################################################### % cat count_files.rb class FileCounter def initialize(dirs) @dirs = dirs end def file_count return @file_count if defined? @file_count @file_count = 0 @dirs.each { |d| count_files_in_dir d } @file_count end def show puts "Number of files: #{file_count}" end private def count_files_in_dir(d) Dir.foreach(d) { |fn| @file_count += 1 if test ?f, "#{d}/#{fn}" } end end FileCounter.new(ARGV.empty? ? ["."] : ARGV).show ########################################################### Both print the number of files in the current directory or in the directories given on the commandline. What's the difference: The Ruby script can have any number of FileCounter objects, the program state is hold (in the above script) by one FileCounter object. The program state in the Perl script is hold by the variables @dirs and $file_count, there can't exist a second $file_count or @dirs. Kind regards, Stefan