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

前端 未结 4 1894
慢半拍i
慢半拍i 2021-01-12 06:15

Given the following two pieces of code:

def hello(z)
  \"hello\".gsub(/(o)/, &z)
end
z = proc {|m| p $1}
hello(z)
# prints: nil



        
4条回答
  •  离开以前
    2021-01-12 06:29

    Things like $1, $2 acts like LOCAL VARIABLES, despite its leading $. You can try the code below to prove this:

    def foo
      /(hell)o/ =~ 'hello'
      $1
    end
    
    def bar
      $1
    end
    
    foo #=> "hell"
    bar #=> nil
    

    Your problem is because the proc z is defined outside the method hello, so z accesses the $1 in the context of main, but gsub sets the $1 in the context of method hello.

提交回复
热议问题