如何在Ruby中编写内联块以包含局部变量作用域?

Ste*_*eve 1 ruby

在JavaScript中,以下惯用语有时用于包含范围

// JavaScript
(function() {
    var x = 0;
    // do stuff
})(); // execute anonymous function in-place

// x is undefined (or its previous value)
Run Code Online (Sandbox Code Playgroud)

您会在Perl中看到以下内容:

{
    local $/ = undef;
    $file_contents = <FILE>;
}
# $/ == "\n"
Run Code Online (Sandbox Code Playgroud)

Ruby中有类似的东西吗?我能想到的最接近的是:

Proc.new
    x = 123
    puts x
end.call
# x is undefined
Run Code Online (Sandbox Code Playgroud)

在Ruby中是否还有另一种更常见的方法可以做到这一点?

mat*_*att 5

如果您的示例x在块之前已经定义,则将无法使用:

x = 7
Proc.new do
    x = 123
    puts x
end.call
# x is now 123
Run Code Online (Sandbox Code Playgroud)

Ruby确实允许您使用以下语法来指定块参数列表中的块局部变量:

x = 7
Proc.new do |;x| # declare x as block local
    x = 123
    puts x
end.call
# x is still 7
Run Code Online (Sandbox Code Playgroud)

之后的任何变量;都被视为该块的局部变量,并且在封闭范围内不会影响名称相似的变量。