1

我对以下代码感到困惑:

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

    puts a.something
    puts "hello"
end

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

4

1 回答 1

4
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
于 2012-04-10T21:25:40.383 回答