bizzare way of calling Procs?

2019-04-17 16:21发布

I found an example code:

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})

I can't figure out what is in square brackets [:var_1] means. Is this some way to call Porc/lambda? I'm confused also because of the Hash-like way for creating Procs in:

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

I would appreciate any help on this matter.

标签: ruby hash
1条回答
唯我独甜
2楼-- · 2019-04-17 16:48

The method callbacks is build so it is receiving a hash. This hash stores procs against each key, hance to execute the proc you need to fatch it from hash using its key:

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.
查看更多
登录 后发表回答