From: HarryO Date: 2002-01-20T08:00:47+09:00 Subject: Re: $_ as default parameter for a function On Sun, 20 Jan 2002 09:42:41 +1100, HarryO wrote: > On Sun, 20 Jan 2002 07:27:41 +1100, Thomas wrote: > > >> How do I write a function that uses the value of $_ in the calling >> scope, so I can get the same behaviour as the many Kernel methods. > > While I don't have an answer to the specific question, it seems to me > that talking about scope for $_ doesn't make sense, since it's a global. > > My first guess is that what happens when the parser sees the "def" for > this method, it takes the CURRENT value for $_ and uses that as the > default value for that parameter. > > Maybe you can do something like ... > > def fred(x = nil) > if x.nil? > x = $_ > end > end Well, just because I was interested, I tried this. Here's what happened def f(x = nil) puts "f() -- $_ = #{$_}" # => "" (so I guess $_ is nil) if x.nil? x = $_ end puts x end $stderr.print "-> " gets puts "$_ = #{$_}" # => whatever I've typed in f() # => "" So, it looks like $_ gets scribbled on as we enter the method. As I say, global variables, whose values are changed by code I didn't write explicitly are not my idea of useful programming features :-( !!