How to set $_ in a method?

H

Heesob Park

Hi all,

I like to set caller's $_ variable in a method, but it did't work for me.
Consider this:

def foo
puts "$_ = #{$_.inspect} enter foo"
$_ = 'def'
puts "$_ = #{$_.inspect} exit foo"
end

$_ = 'abc'
puts "$_ = #{$_.inspect} before foo"
foo
puts "$_ = #{$_.inspect} after foo"


The result is:
$_ = "abc" before foo
$_ = nil enter foo
$_ = "def" exit foo
$_ = "abc" after foo

I noticed $_ is is local to the current scope.
Is it impossible to set the caller's $_ variable in a method without
using binding and eval?


Thanks,

Park Heesob
 
B

Bertram Scharpf

Hi,

Am Freitag, 12. Jun 2009, 16:45:51 +0900 schrieb Heesob Park:
I like to set caller's $_ variable in a method, but it did't work for me.
[...]
I noticed $_ is is local to the current scope.
Is it impossible to set the caller's $_ variable in a method without
using binding and eval?

$_ has some special meanings in Kernel.gets, Kernel.sub, Regexp#~
etc. This comes in handy for -ne/-pe option oneliners. You
shouldn't use it outside that (if you don't know what you do).

Bertram
 
D

Daniel Berger

-----Original Message-----
From: Bertram Scharpf [mailto:[email protected]]
Sent: Friday, June 12, 2009 5:18 AM
To: ruby-talk ML
Subject: Re: How to set $_ in a method?

Hi,

Am Freitag, 12. Jun 2009, 16:45:51 +0900 schrieb Heesob Park:
I like to set caller's $_ variable in a method, but it did't work for me.
[...]
I noticed $_ is is local to the current scope.
Is it impossible to set the caller's $_ variable in a method without
using binding and eval?

$_ has some special meanings in Kernel.gets, Kernel.sub, Regexp#~
etc. This comes in handy for -ne/-pe option oneliners. You
shouldn't use it outside that (if you don't know what you do).

Except we're trying to match the zlib.c spec. Specifically,
rb_gzreader_gets() in zlib.c:

static VALUE
rb_gzreader_gets(argc, argv, obj)
int argc;
VALUE *argv;
VALUE obj;
{
VALUE dst;
dst = gzreader_gets(argc, argv, obj);
if (!NIL_P(dst)) {
rb_lastline_set(dst);
}
return dst;
}

The rb_lastline_set() call sets $_. What's the equivalent in pure Ruby? If
it's possible to do within a C extension, it ought to be possible to do in
pure Ruby.

Regards,

Dan
 
C

Charles Oliver Nutter

The rb_lastline_set() call sets $_. What's the equivalent in pure Ruby? If
it's possible to do within a C extension, it ought to be possible to do in
pure Ruby.

It is not possible, which is why backref and lastline should be
banned. $_ and $~ are treated specially and can only be set across
calls from C code (or Java code in JRuby).

- Charlie
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,071
Latest member
MetabolicSolutionsKeto

Latest Threads

Top