4 ms·
This is one area where Matz kept too much of Perl. Thankfully, it's rare to see Ruby programmers making heavy use of these.
by ef4 14y ago
This is one area where Matz kept too much of Perl. Thankfully, it's rare to see Ruby programmers making heavy use of these.
- rjbond3rd 14y agoIt'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 $!)
- wonnage 14y agoThe 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.
- briangonzalez 14y agoTrue, but I have seen -- $:.unshift File.dirname(__FILE__) -- used quite a bit in the wild, especially in MacRuby projects.
- vidarh 14y ago$: and $1 .. $9 are relatively frequently used. Most of the other ones are rare - several of them I've never seen used at all.
- charliesome 14y agoI use $1, $2, $3, etc. quite often. $' and $` are also useful for throwaway scripts.
- riffraff 14y agofor throwaway irb sessions, I often use stuff like foo.map { |x| x.something rescue $! }
- ZoFreX 14y agoIf you write your shell scripts in Ruby they do come in handy. I certainly wouldn't use them outside of that context.
- draegtun 14y agoEspecially 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 :)