proc 在 irb 中改变类

发布于 2024-11-24 07:08:04 字数 314 浏览 4 评论 0原文

就在我以为我已经全神贯注于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

懵少女 2024-12-01 07:08:04

首先,您的代码中存在语法错误,因此我假设您的意思是 x = Proc.new {|name| "Hello #{name}"} 而不是 x = Proc.new (|name| "Hello #{name}"}

其次,当我运行您的示例代码时,我不' 但是,如果 name 变量的命名与存储 proc的

变量名称相同(在示例中为 x),那么您就是使用 1.9 之前的 ruby​​ 版本,您将遇到此行为。

这是一个示例(我使用 x 作为块变量的名称,这是 ruby​​ 1.8.7):

>> x = Proc.new {|x| "Hello #{x}"}
=> #<Proc:0x00000001013335b8@(irb):1>
>> x.class
=> Proc
>> x.call("Bob")
=> "Hello Bob"
>> x.class
=> String
>> x
=> "Bob"

发生这种情况的原因是因为您可以覆盖在当前范围之外定义的变量在 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 of x = 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):

>> x = Proc.new {|x| "Hello #{x}"}
=> #<Proc:0x00000001013335b8@(irb):1>
>> x.class
=> Proc
>> x.call("Bob")
=> "Hello Bob"
>> x.class
=> String
>> x
=> "Bob"

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文