Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Ruby Foundations Procs & Lambdas Working With Procs & Lambdas

Víctor Rico
Víctor Rico
17,808 Points

Is this really a good example about why procs and lambdas are useful?

I changed the Paper class a bit to see if I could make it work with less code. This is what I did and it worked:

class Paper 
    def initialize(&block) 
        yield self if block_given?
    end

    def set_variable(kind, val)
        return [kind, val].join ": "
    end

    def title(value)
        @title = set_variable "TITLE", value
    end

    def heading(value)
        @heading = set_variable "HEADING", value
    end

    def body(value)
        @body = set_variable "BODY", value
    end

    def display
        puts @title
        puts "______________________"
        puts @heading
        puts "______________________"
        puts @body
        puts "______________________"
    end
end

paper = Paper.new do |p| 
    p.title     "My awesome paper"
    p.heading "This is my paper"
    p.body      "The entire contents of my paper would go here."
end
paper.display

Could anyone explain a better scenario for woking with procs or lambdas?

Thank you very much!

Víctor Rico
Víctor Rico
17,808 Points

I think blocks are like Javascript anonymous functions:

some_method(function() {
  //Code here...
});

And procs and lambdas would be something like this:

var example = function(arg1, arg2) {
  //Code here...
};

Am I right?