From: Jacob Fugal Date: 2006-02-03T02:16:11+09:00 Subject: Re: Chomping and stomping 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