Questions tagged [pseudo-globals]

A pseudo-global in Ruby is a variable that is in the local scope, even though its name starts with a $ sign.

A pseudo global in is a variable that refers to a value in the current scope, but whose name starts with a $. All pseudo globals are references to parts of the primary pseudo global $~. Pseudo globals look like global variables but are in fact local variables.

External links

6 questions
9
votes
5 answers

Using $1, $2, etc. global variables inside method definition

Given the following two pieces of code: def hello(z) "hello".gsub(/(o)/, &z) end z = proc {|m| p $1} hello(z) # prints: nil def hello z = proc {|m| p $1} "hello".gsub(/(o)/, &z) end hello # prints: "o" Why are the outputs of these two…
Bogdan Gusiev
  • 8,027
  • 16
  • 61
  • 81
8
votes
3 answers

Why are only a limited number of regular expression captures stored in `global_variables`?

If I do a match with a regular expression with ten captures: /(o)(t)(th)(f)(fi)(s)(se)(e)(n)(t)/.match("otthffisseent") then, for $10, I get: $10 # => "t" but it is missing from global_variables. I get (in an irb session): [:$;, :$-F, :$@, :$!,…
Sagar Pandya
  • 9,323
  • 2
  • 24
  • 35
7
votes
4 answers

How to override `File::SEPARATOR`

Documents for File.join states that: join(string, ...) → string Returns a new string formed by joining the strings using File::SEPARATOR. File.join("usr", "mail", "gumby") #=> "usr/mail/gumby" However, the result below shows a different…
cozyconemotel
  • 1,121
  • 2
  • 10
  • 22
6
votes
3 answers

Why are Ruby global strings, like $&, ignoring mutations without error?

I'm learning Ruby (2.0) and this just surprised me: s = "1234" s =~ /\d+/ $& ==> "1234" # as expected, $& contains the matched string $&.slice!(-2..-1) # should mutate string $& ==> "1234" # what? s.slice(-2..-1) s ==> "12" …
Rob N
  • 15,024
  • 17
  • 92
  • 165
1
vote
1 answer

How to use '$MATCH' as an alias of '$&'

According to this document, $MATCH is an alias of $&, and I want to use it for readability. But it doesn't work in my environment. '1234-4567'.match(/\d{4}-/){ $& } # => "1234-" '1234-4567'.match(/\d{4}-/){ $MATCH } # => nil What am I…
ironsand
  • 14,329
  • 17
  • 83
  • 176
0
votes
2 answers

gsub caching groups?

If I run this code: "Retailer Staff $5.60".gsub(/.*\$(\d+(\.\d+)?).*/, $1) # => 5.60 and then I change the value to: "Retailer Staff $5".gsub(/.*\$(\d+(\.\d+)?).*/, $1) # => 5.60 the answer stays at 5.60. Then, if I run the same line again, I…
Mirror318
  • 11,875
  • 14
  • 64
  • 106