From: 7stud -- Date: 2008-01-24T11:18:01+09:00 Subject: Re: Reusing chunks of code John Maclean wrote: > Hi guys, > > I wanted to avoid using the word "block" as it's such a key word in > Ruby. > I'm performing the same test twice here and there must be a way to > reuse it... > =begin > Mon Jan 21 12:51:19 GMT 2008 > simple plays with dirs > =end > > # create a "singleton object" > testobj = Object.new > > # play with the object - just a start ;-) > def testobj.homePlay > startDir = Dir.pwd > p "current dir is #{startDir}" > puts "Dir.getwd == Dir.pwd" if Dir.getwd == Dir.pwd > > # check for ~/ > if Dir.exist?("#{ENV["HOME"]}") > p "changing to ~/" > else > p "cannot find your home dir. STOP!" > exit > end > > Dir.chdir > > # have we changed directory from where we started? > if Dir.pwd == startDir > p "current dir is still #{startDir}. pwd not changed ;-)" > else > p "pwd has changed to Dir.pwd" > end > > print "file listing of your home dir...\n\n" > > p Dir.entries(".").sort # << this an array > print "\n\nlisting ../ \n\n" > Dir.foreach("..") {|x| p x} > > end > # end of method testobj.dirPlay > > def testobj.procPlay > px = "/proc/" > if Dir.exist?("#{px}") > p "#{px} dir found - continue" > else > p "#{px} not found - STOP!" > exit > end > end > > # send message to object > testobj.homePlay > testobj.procPlay > > __END__ > The question is how to reuse the "testing if directory exists chunk of > code"? I'm still thinking procedurally I guess. > Regards, > > John Maclean > MSc (DIC) > +44 7739 171 531 > puts "Dir.getwd == Dir.pwd" if Dir.getwd == Dir.pwd According to my book, getwd() and pwd() are the same method. > if Dir.exist?("#{ENV["HOME"]}") Dir.exist? I don't have that method. Is it new? > The question is how to reuse the "testing if directory exists chunk of > code"? I'm still thinking procedurally I guess. Do you mean this part: > if Dir.exist?("#{ENV["HOME"]}") > p "changing to ~/" > else > p "cannot find your home dir. STOP!" > exit > end You could write: def check_dir(some_str) if Dir.exist?(some_str) p "changing to ~/" else p "cannot find your home dir. STOP!" exit end end but that isn't very general since you hardcoded the message to output. You could pass two messages in as arguments, but really what does the output message have to do with checking whether the dir exists? So that leaves you with something like this: def check_dir(some_str) return Dir.exist?(some_str) end And you could write: if check_dir("some dir") puts 'yep' else puts 'nope' end But that code just wraps a definition around a ruby method, so why not just call the method directly--like you did in the first place: if Dir.exist?("some dir") puts 'yep' else puts 'nope' end -- Posted via http://www.ruby-forum.com/.