Setting $0

I’m very new to ruby but I’ll take a stab at this. Am sure that someone can
correct me or elaborate if I am off track.

By convention, variables starting with ‘$’ are globals in ruby. The '$0’
variable is a special variable that always exists and contains the name of
the script executing. Ruby is identical to Perl in this respect.

When the $0 object is first created it has a length that is correct for the
length of the filename. You can check the length with ‘$0.length’ - for a
file called t.rb the length is 9, for a file called trb.rb it is 11, and so
on. Not sure why it seems to be longer than the actual filename.

When you assign a string to $0 within your code it seems that it is only
storing (or displaying…?) the number of characters corresponding to the
length of the filename.

So if your file is called t.rb you will see ‘My Applic’.
if your file is called tr.rb you will see ‘My applica’.
if your file is called reallylongname.rb you will see the entire string.

Not sure if this is a bug or expected behaviour…I guess that $0 should be
kept for holding the filename, and not later assigned with anything else…

Zach Chinnery

···

-----Original Message-----
From: Joel VanderWerf [mailto:vjoel@PATH.Berkeley.EDU]
Sent: Thursday, 18 December 2003 5:09 PM
To: ruby-talk@ruby-lang.org
Subject: setting $0

With the following file, t.rb,


#!/usr/bin/env ruby

$0 = 'My Application’
puts $0

the output is:

$ ruby -v t.rb
ruby 1.8.1 (2003-12-05) [i686-linux]
My Applicati

Why does it get truncated?

Hi,

When the $0 object is first created it has a length that is correct for the
length of the filename. You can check the length with ‘$0.length’ - for a
file called t.rb the length is 9, for a file called trb.rb it is 11, and so
on. Not sure why it seems to be longer than the actual filename.

It icnludes also arguments, and the interpreter name length.

When you assign a string to $0 within your code it seems that it is only
storing (or displaying…?) the number of characters corresponding to the
length of the filename.

So if your file is called t.rb you will see ‘My Applic’.
if your file is called tr.rb you will see ‘My applica’.
if your file is called reallylongname.rb you will see the entire string.

Not sure if this is a bug or expected behaviour…I guess that $0 should be
kept for holding the filename, and not later assigned with anything else…

Feature, to change command line shown by ps.

$ ruby -e ‘$0 = “Sleeping…zzz”; sleep’ &
[1] 5349
$ ps $!
PID TTY STAT TIME COMMAND
5349 pts/4 S 0:00 Sleeping…zzz

If you want change $0 value inside a script (without ps), alias
it. You can see an example in ext/extmk.rb.

$progname = $0
alias $PROGRAM_NAME $0
alias $0 $progname

···

At Thu, 18 Dec 2003 15:32:38 +0900, Zach Chinnery wrote:


Nobu Nakada