Re:Cryptic Ruby Global Variables and Their Meanings
by ef4 on Sunday September 16, 2012 @10:47PM
(#4531150)
This is one area where Matz kept too much of Perl. Thankfully, it's rare to see Ruby programmers making heavy use of these.
[ Parent
| on HN ]
Re:Cryptic Ruby Global Variables and Their Meanings
by wonnage on Monday September 17, 2012 @12:33AM
(#4531336)
The former ubiquity of Perl made most of these common knowledge. For example, $? works in both Perl and bash (actually, I don't know which did this first...). So in the context of shell scripts, where Ruby started, having these magic globals makes a lot of sense.
IMO they can make code easier to understand, once you've learned what they mean. $2 conveys the same idea as matches[2] without having to think about array indices, and why the matches aren't zero-indexed like a normal array. This is obviously totally subjective.
Re:Cryptic Ruby Global Variables and Their Meanings
by draegtun on Monday September 17, 2012 @07:33AM
(#4532067)
Especially when Ruby has no way of scoping these variables... unlike Perl:
{
# level 1
local $\ = "[1]\n";
some_print_operation();
{
# level 2
local $\ = "[2]\n";
some_print_operation();
}
# level 1 again
some_print_operation();
}
# $\ back to what it was before all this :)
Re:Cryptic Ruby Global Variables and Their Meanings
by briangonzalez on Monday September 17, 2012 @02:09AM
(#4531457)
True, but I have seen -- $:.unshift File.dirname(__FILE__) -- used quite a bit in the wild, especially in MacRuby projects.
Re:Cryptic Ruby Global Variables and Their Meanings
by vidarh on Monday September 17, 2012 @05:20AM
(#4531784)
$: and $1 .. $9 are relatively frequently used. Most of the other ones are rare - several of them I've never seen used at all.
Re:Cryptic Ruby Global Variables and Their Meanings
by rjbond3rd on Sunday September 16, 2012 @11:16PM
(#4531198)
It's also rare to see them heavily used in Perl nowadays. Lots of recent code doesn't use them at all (e.g., with autodie, no need for $!)
Re:Cryptic Ruby Global Variables and Their Meanings
by ZoFreX on Monday September 17, 2012 @06:19AM
(#4531897)
If you write your shell scripts in Ruby they do come in handy. I certainly wouldn't use them outside of that context.
Re:Cryptic Ruby Global Variables and Their Meanings
by charliesome on Monday September 17, 2012 @02:19AM
(#4531469)
I use $1, $2, $3, etc. quite often. $' and $` are also useful for throwaway scripts.