pseudo-globals

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

限于喜欢 提交于 2019-12-19 06:05:07
问题 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 pieces of code different? Is there a way to pass a block to gsub from outside of the method definition so that the variables $1 , $2 would be evaluated in the same way as if the block was given inside the method definition? 回答1: Why the output is different? A

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

我的未来我决定 提交于 2019-12-19 06:04:07
问题 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 pieces of code different? Is there a way to pass a block to gsub from outside of the method definition so that the variables $1 , $2 would be evaluated in the same way as if the block was given inside the method definition? 回答1: Why the output is different? A