proc 在 irb 中改变类
就在我以为我已经全神贯注于 procs 和 procs 的时候了。 lambdas 会发生这种情况...
irb> x = Proc.new{|name| "Hello #{name}"}
irb> x.class #=> Proc
irb> x.call("Bob") #=> "Hello Bob"
irb> x.class #=> String
irb> x #=> "Bob"
为什么 x
在调用时会更改其类?
我在这里误解和/或做错了什么?
Just when I thought I had my head wrapped around procs & lambdas this happens...
irb> x = Proc.new{|name| "Hello #{name}"}
irb> x.class #=> Proc
irb> x.call("Bob") #=> "Hello Bob"
irb> x.class #=> String
irb> x #=> "Bob"
Why is x
changing its class when called?
What am I misunderstanding and/or doing wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您的代码中存在语法错误,因此我假设您的意思是
x = Proc.new {|name| "Hello #{name}"}
而不是x = Proc.new (|name| "Hello #{name}"}
。其次,当我运行您的示例代码时,我不' 但是,如果
name
变量的命名与存储 proc的变量名称相同(在示例中为
x
),那么您就是使用 1.9 之前的 ruby 版本,您将遇到此行为。这是一个示例(我使用
x
作为块变量的名称,这是 ruby 1.8.7):发生这种情况的原因是因为您可以覆盖在当前范围之外定义的变量在 ruby pre 1.9 中,这种行为称为遮蔽,并被描述为 此处。
First of all, there's a syntax error in your code, so I'm assuming you mean
x = Proc.new {|name| "Hello #{name}"}
instead ofx = Proc.new (|name| "Hello #{name}"}
.Second, when I run your example code I don't get that behavior.
However, if the
name
variable were to be named the same as the variable name where you store the proc (x
in your example), and you were using a ruby version prior to 1.9, you will get this behavior.Here's an example of that (I use
x
as the name of the block variable, and this is ruby 1.8.7):The reason that happens is because you can overwrite a variable defined outside of the current scope in ruby pre 1.9. In ruby 1.9 this behavior is called shadowing, and is described here.