Ruby Procs Are Amazing!

I just got through the Codeacademy Procs section and got so excited I tweeted about them and emailed my girlfriend explaining what Procs are and why they’re so cool…bad I know. Luckily she works in finance and is a total excel geek so she can empathize and won’t think I’m a complete weirdo.

Tweet about how cool Ruby Procs are

Email about how cool Ruby Procs are

Since I already tweeted and sent an email about Procs I figured I’d post about them to round things out.

Why Procs are Cool

Procs allow you to save a block of code, something like { |x| x *3 } which is saying take whatever I give you (x) and multiply it by 3. What you can then do with this is pass it to methods.

So for example, I have an array of people’s heights, like so:

1
array = [4.5, 5, 6, 3.5, 3]

And I want to get all the heights that are above 4 feet tall because that’s how tall you have to be to ride the ride…le duh.

I could write some long method called rubyover_4_feet where I pass it the array and then it returns the heights that are above 4 feet tall. But that would require 9 lines of code…maybe less but that’s how many lines it took me.

1
2
3
4
5
6
7
8
9
def over_4_feet(array)
    new_arr = []
    array.each do |i|
        unless i < 4
            new_arr << i
        end
    end
    return new_arr
end

Instead I can call the method .select on the array and pass it a Proc that tells it to only select heights that are taller than 4 feet.

Below is a proc that checks for being over 4 feet tall. Then I just pass that proc to the .select method telling it to only “select” heights over 4 feet.

1
2
3
over_4_feet = Proc.new { |x| x >= 4 }

array.select(&over_4_feet)

So what took me 9 lines of code I did in 1, since passing the Proc to select is the same as calling the over_4_feet method.

AMAZING!!!


Copyright © 2015 - Kyle Doherty. Powered by Octopress