From: John Maclean Date: 2006-02-03T03:29:54+09:00 Subject: Re: Chomping and stomping Chaps, Thanks for those speedy replies Following on from #thanks to you guyson the list for clearing this up jayeola@tp20$ cat bin/acid/classes/testing/testchomp.rb #!/usr/bin/ruby -w def chomper xx = gets.chomp until (xx= gets.chomp) == "qq" puts "hit me with a squirell!" end xx end chomper # ^^ the above works. :) # This is supposed to do the same as the above but write to a file... here's version 1 #!/usr/bin/ruby -w def testwrite puts "hit me with a squirell!" until $_ =="qq" gets.chomp! if $_ != "qq" File.open("testfile", "a") { |file| file.write($_) } end end end testwrite here's version 1 jayeola@tp20$ cat bin/acid/classes/testing/write_file2.rb #!/usr/bin/ruby -w def testwrite xx = gets.chomp until (xx.gets.chomp) == "qq" puts "hit me with a squirell!" File.open("testfile", "a") { |file| file.write(xx) } end end testwrite On Fri, 3 Feb 2006 02:16:11 +0900 Jacob Fugal wrote: > On 2/2/06, John Maclean wrote: > > #!/usr/bin/ruby -w > > def chomper > > xx = gets.chomp! > > until $_ == "qq" > > puts "hit me with a squirell!" > > xx = gets.chomp! > > xx > > end > > end > > > > chomper > > > > # this works but surely there must be a way to incoporate a variable > > in there? > > > > #!/usr/bin/ruby -w > > def chomper > > xx = gets.chomp! > > until xx == "qq" > > puts "hit me with a squirell!" > > xx > > end > > end > > > > #this don't work. > > String#chomp! is a "destructive" operation. This means that it acts in > place on its receiver and, in this case, returns nil. So what's > happening here is that Kernel#gets creates a String object, chomp! is > sent to that object, the object is modified in place and nil returned. > That's why xx is nil. As you discovered in your first example, the > String object returned by Kernel#gets is stored in $_. Accessing it > this way isn't a bset practice however. > > What you probably want instead is to use the non-destructive twin (the > Good Twin) of String#chomp!, namely String#chomp. Notice the lack of > the bang (!). The bang is generally (but not always) an indicator that > the method is destructive. String#chomp creates a chomped copy of it's > receiver and returns it. Replacing chomp! with chomp it should work: > > #!/usr/bin/ruby -w > def chomper > xx = gets.chomp > until xx == "qq" > puts "hit me with a squirell!" > xx > end > end > > puts chomper > > Jacob Fugal > > > -- John Maclean MSc (DIC) 07739 171 531