0

I read following ruby code:

def callbacks(procs)
  procs[:starting].call     # line 1
  puts "Still going"
  procs[:finishing].call    # line 2
end

callbacks(:starting => Proc.new { puts "Starting" },   # line 3
          :finishing => Proc.new { puts "Finishing" }) # line 4

I can guess what it dose. But I don't know what :starting and :finishing in line 1 & 2 mean, and what :starting=> in line 3 and :finishing=> in line 4 mean. It's even hard to find a keyword to google.

Could anybody explain line 1,2,3,4 to me? If you may refer some official doc, that will be even better.

TieDad
  • 9,143
  • 5
  • 32
  • 58

2 Answers2

3

procs is a Hash, procs[:starting] refers to the value for key :starting, which is set by:

:starting => Proc.new { puts "Starting" }

The method call is equivalent to:

h = {}
h[:starting] = Proc.new { puts "Starting" }
h[:finishing] = Proc.new { puts "Finishing" }
callbacks(h)
Stefan
  • 109,145
  • 14
  • 143
  • 218
1

But I don't know what :starting and :finishing in line 1 & 2 mean

:starting and :finishing are the hash keys of the hash procs.

what :starting=> in line 3 and :finishing=> in line 4 mean.

You are sending a Hash object as an argument via the method callbacks.

Read here Hash.

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317