Let’s say I have the following array:
arr = [[5, 1], [2, 7]]
and I want to find the minimum element, comparing the second element of the elements. The minimum element will be [5, 1] since 1 is less than 7. I can use the following code:
arr.min {|a,b| a[1] <=> b[1]}
For calculating the maximum, I can do the same:
arr.max {|a,b| a[1] <=> b[1]}
That gives [2, 7].
I use the same block all the time. I would like to have that block somewhere and provide it to the min/max function. I hoped something like:
blo = lambda {|a,b| a[1] <=> b[1]}
arr.min blo
would work, but it didn’t. Any idea on how I can do this?
Use the
&operator to turn aProcobject into a block.