如何使块局部变量默认在ruby 1.9? [英] How to make block local variables the default in ruby 1.9?

查看:96
本文介绍了如何使块局部变量默认在ruby 1.9?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby 1.9允许定义一个块的局部变量,并且不会在外部范围内关闭同名的变量:

Ruby 1.9 gives the ability to define variables that are just local to a block and do not close over variables of the same name in an outer scope:

x = 10
proc { |;x|
    x = 20
}.call
x #=> 10

我想将此行为默认为我定义的一些块 - |; x,y,z |语法(注意分号)。

I would like to have this behaviour as default for some blocks I define - without having to use the |;x, y, z| syntax (note the semicolon).

我不认为Ruby允许这个本机,但是可以破解这个功能吗?

I do not think Ruby allows this natively but is it possible to hack this functionality?

我目前有一个解决方案,但它是相当丑陋的,因为它需要检查看看哪些本地已在块的结尾更改,然后将其还原到它们的值之前的块。我不介意如果你的解决方案需要指定哪些变量是block-local在块的开始 scope(:x){x = 20}

I have one solution currently but it's quite ugly as it requires checking to see which locals have changed at the end of a block and then reverting them to their values prior to the block. I do not mind if your solution requires specifying which variables are block-local at the start of the block i.e scope(:x) { x = 20 }

推荐答案

我选择的解决方案是基于bobbywilson0的想法。这是它的工作原理:

The solution I am choosing is based on bobbywilson0's idea. Here is how it works:

x = 99
y = 98

scope { |x, y|
    x = 20
    y = 30
}

x #=> 99
y #=> 98 

这是有用的范围在范围的开始处创建,并且不关闭任何在其外部定义的变量,它们也在范围的末尾进行GC。

This is useful as the variables used in the scope are created at the start of the scope and do not close over any variables defined outside it, they are also GC'd at the end of the scope.

这里是实现:

def scope(&block)
    num_required = block.arity >= 0 ? block.arity : ~block.arity
    yield *([nil] * num_required)
end

此解决方案还将默认值考虑在内,使其在功能上等同于lisp中的 let *

This solution also takes default values into account making it functionally equivalent to a let* in lisp.

scope { |x = 20, z = (x * 3)| 
    x #=> 20
    z #=> 60
}

我在此处的博客: http://banisterfiend.wordpress.com/2010/01/07/ controls-object-scope-in​​-ruby-1-9 /

这篇关于如何使块局部变量默认在ruby 1.9?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆