Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby is it possible to create a local variable explicitly

e.g.

x = 123
p = Proc.new {
  x = 'I do not want change the value of the outer x, I want to create a local x'
}

In Ruby Is there something the same as "my" keyword in Perl ?

like image 615
bdimych Avatar asked Feb 16 '23 09:02

bdimych


2 Answers

As per the Perl documentation of my,I think you are looking for something like below in Ruby:-

x = 123 
p = Proc.new {|;x|  
  x = 'I do not want change the value of the outer x, I want to create a local x'
}
p.call 
# => "I do not want change the value of the outer x, I want to create a local x"
x # => 123
like image 92
Arup Rakshit Avatar answered Mar 05 '23 18:03

Arup Rakshit


Beware! (Related, though not exactly what you're asking...)

The rules for variable scope changed between 1.8 and 1.9. See Variable Scope in Blocks

x = 100
[1,2,3].each do |x|

behaves differently in the different versions. If you declare a variable in a block's || that has the same name as a variable outside the block, then in 1.8 it will change the value of the outer variable, and in 1.9 it will not.

like image 37
ChrisPhoenix Avatar answered Mar 05 '23 19:03

ChrisPhoenix