【问题标题】:Understanding procs in ruby了解 ruby​​ 中的 procs
【发布时间】:2012-04-10 21:12:09
【问题描述】:

我对以下代码感到困惑:

Proc.new do |a|
    a.something "test"

    puts a.something
    puts "hello"
end

它在运行时不会抛出任何错误。但是,puts 语句都没有打印任何内容。我对a.something“作业”很好奇。也许这是一个省略了括号的方法调用。 上面的代码发生了什么?

【问题讨论】:

  • 该代码没有做任何事情,除了创建一个永远不会运行的闭包。
  • 您实际上是在运行Proc,还是只是在声明它?
  • 它是从一个方法(不是我写的)返回的。更一般的红宝石问题:上面示例中a 上的something 字段如何工作?可以在 ruby​​ 中随时在对象上声明字段吗?
  • @Sunday: a.something 是一种在块的第一行使用单个参数调用而在第三行不使用参数调用的方法。
  • 你只是在创建一个从未被调用甚至没有名字的 Proc。就像您尝试过的一样:String.new("hello")。该行创建了一个新字符串,但没有对其进行任何处理。你正在这样做: Proc.new({|a| ...}) 它只是漂浮在空间中。

标签: ruby variable-assignment proc


【解决方案1】:
Proc.new ...             # create a new proc

Proc.new{ |a| ... }      # a new proc that takes a single param and names it "a"

Proc.new do |a| ... end  # same thing, different syntax

Proc.new do |a|
  a.something "test"     # invoke "something" method on "a", passing a string
  puts a.something       # invoke the "something" method on "a" with no params
                         # and then output the result as a string (call to_s)
  puts "hello"           # output a string
end

由于 proc 中的最后一个表达式是 puts,它总是返回 nil,所以 proc 如果曾经调用过,其返回值将是 nil

irb(main):001:0> do_it = Proc.new{ |a| a.say_hi; 42 }
#=> #<Proc:0x2d756f0@(irb):1>

irb(main):002:0> class Person
irb(main):003:1>   def say_hi
irb(main):004:2>     puts "hi!"
irb(main):005:2>   end
irb(main):006:1> end

irb(main):007:0> bob = Person.new
#=> #<Person:0x2c1c168>

irb(main):008:0> do_it.call(bob)  # invoke the proc, passing in bob
hi!
#=> 42                            # return value of the proc is 42

irb(main):009:0> do_it[bob]       # alternative syntax for invocation
hi!
#=> 42

【讨论】:

  • 这是一个很好的例子,谢谢。关于返回值的有趣点(在您的示例中为 42)。
  • @SundayMonday 任何块(以及方法和语句)的“返回值”始终是语句中最后一个表达式的值。
  • 另一种调用lamba/proc的语法:do_it.(bob).
  • @Phrogz 好吧,前提是没有早期的return 声明,但我在这里可能有点迂腐。
  • @andrew 或者如果 next 被调用,会变得更加迂腐。
猜你喜欢
  • 2015-11-06
  • 2014-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-21
相关资源
最近更新 更多