Ruby中如何显式声明局部变量?
- 内容介绍
- 文章标签
- 相关推荐
本文共计304个文字,预计阅读时间需要2分钟。
例如,在Ruby中:rubyx=123p=Proc.new { x='I do not want to change the value of the outer x, I want to create a local x' }在Ruby中,这与Perl中的`my`关键字有相似之处。Ruby中使用局部变量和实例变量时,不需要使用特定的关键字。例如,在Proc块中修改的变量`x`是局部的,只在该Proc内部可见。
在Perl中,`my`关键字用于声明局部变量:perlmy $x=123;my $p=sub { $x='I do not want to change the value of the outer x, I want to create a local x' };在这种情况下,Perl中的`$x`和Ruby中的`x`都是局部变量,它们的值在子例程或Proc内部被修改,而不会影响外部变量。因此,可以说Ruby中的Proc和Perl中的`my`关键字在处理局部变量方面有相似的功能。
例如x = 123 p = Proc.new { x = 'I do not want change the value of the outer x, I want to create a local x' }
在Ruby中是否有与Perl中的“my”关键字相同的东西?
根据 my的Perl文档,我认为你在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
本文共计304个文字,预计阅读时间需要2分钟。
例如,在Ruby中:rubyx=123p=Proc.new { x='I do not want to change the value of the outer x, I want to create a local x' }在Ruby中,这与Perl中的`my`关键字有相似之处。Ruby中使用局部变量和实例变量时,不需要使用特定的关键字。例如,在Proc块中修改的变量`x`是局部的,只在该Proc内部可见。
在Perl中,`my`关键字用于声明局部变量:perlmy $x=123;my $p=sub { $x='I do not want to change the value of the outer x, I want to create a local x' };在这种情况下,Perl中的`$x`和Ruby中的`x`都是局部变量,它们的值在子例程或Proc内部被修改,而不会影响外部变量。因此,可以说Ruby中的Proc和Perl中的`my`关键字在处理局部变量方面有相似的功能。
例如x = 123 p = Proc.new { x = 'I do not want change the value of the outer x, I want to create a local x' }
在Ruby中是否有与Perl中的“my”关键字相同的东西?
根据 my的Perl文档,我认为你在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

