Posted in Procs


Procs are new concept to me. As I’ve stated before, I work in large legacy app that started life as a Rails 2 app. I started with the group when they were at 3.2. Procs are used in complex processes within the application and a process that is breaking for some of our users…while traversing the code base getting myself familair with the workflow, I came across this bit of code:

merge_proc = proc do |key, old_value, new_value|

(old_value + new_value).uniq


To preface this code, there was nothing to instantiate any of the values within the proc so this led me down the path that the proc has deeper purpose than meets the eye. If I build this out in IRB, then a proc object is created.

If I look at how merge_proc is defined then it is a block that maintains local variables and how they will be processed. So it will take 2 arrays, combine them and then drop the duplicates in the above example.

Lets try another example:

h1, h2 = {},{}

h1[:object1] = %w(a1 a2 a3)

h2[:object1] = %w(a3 a4 a5)


=> {:object1=>[“a1”, “a2”, “a3”, “a4”, “a5” ]}

The standard merge method overwrites values in h1.

Lets change the way the proc is defined:

merge_proc ={|key, old, new| old + new }

h1.merge(h2, &merge_proc)

=> {:object1=>[“a1”, “a2”, “a3”, “a3”, “a4”, “a5” ]}

That is pretty cool.