我对以下代码感到困惑:
Proc.new do |a|
a.something "test"
puts a.something
puts "hello"
end
它在运行时不会抛出任何错误。但是,puts
语句都不会打印任何内容。我很好奇 a.something
“作业”。也许这是一个省略了括号的方法调用。 上面的代码发生了什么?
最佳答案
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
关于ruby - 了解 ruby 中的 proc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10096534/