调用Procs的奇怪方式?

时间:2014-04-30 09:57:04

标签: ruby hash

我找到了一个示例代码:

def callback(procs)
  procs[:var_1]
  puts "Proceed"
  procs[:var_2]
end

callback(:var_1 => Proc.new {block_1},
         :var_2 => Proc.new {block_2})

我无法弄清楚方括号[:var_1]的含义。这是一种调用Porc / lambda的方法吗?我也很困惑,因为用于创建Procs的类似Hash的方式:

callback(:start => Proc.new {puts "The begining of the CALLBACK"},
         :finish => Proc.new {puts "The ending of the CALLBACK"})

我很感激有关此事的任何帮助。

1 个答案:

答案 0 :(得分:4)

构建方法回调是因为它正在接收哈希。这个哈希存储针对每个密钥的procs,然后执行你需要使用其密钥从哈希中获取它的proc:

hash = { :start => Proc.new {puts "The begining of the CALLBACK"},
         :finish => Proc.new {puts "The ending of the CALLBACK"} }

hash[:start]       #=> proc object you can call `call` on.
相关问题