ruby - 了解 ruby​​ 中的 proc

标签 ruby variable-assignment proc

我对以下代码感到困惑:

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/

相关文章:

ruby - Ruby 1.8 和 Ruby 1.9 中 `Array#to_s` 的区别

Ruby - 方法属性

ruby - 按方法的结果对哈希进行排序,将 nil 结果排序到底部

namespaces - 如何在 tcl 命名空间中定义一个 proc

c++ - linux new 后无变化

ruby - 是否可以在不实际发送或读取数据的情况下查明 ruby​​ 套接字是否处于 ESTABLISHED 或 CLOSE_WAIT 状态?

c# - .NET C# 设置由 lambda 选择器定义的字段的值

java - Java 中的条件赋值

c++ - 当您在公式中分配变量时会发生什么?

ruby - 传递给 `instance_exec` 时如何执行 proc