4

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 ?

bdimych
  • 291
  • 2
  • 8

2 Answers2

7

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
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
1

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.

Community
  • 1
  • 1
ChrisPhoenix
  • 1,040
  • 1
  • 11
  • 16