Skip to content
Tags

of blocks, procs and lamdas

May 31, 2011

1. Blocks can be passed to a method implicitly

def testing_blocks
  yield
end

testing_blocks do
  puts "Hello"
end

Hello
=> nil

2. Blocks can be passed to a method explicitly

def testing_blocks &block
  yield
  block.call
end

testing_blocks do
  puts "Hello"
end

Hello
Hello
 => nil

3. The ampersand converts a block to an object

def testing_blocks &block
  block
end

testing_blocks do
  puts "Hello"
end

  => #<Proc:0x0000010b155390@<main>:4>

4. The block object has class Proc

ruby-1.9.2-p180 :091 > object = testing_blocks { puts "hello" }
=> #<Proc:0x0000010b17e6c8@(irb):23>
ruby-1.9.2-p180 :092 > object.class
 => Proc
4. Calling unary ampersand on block converts it to a Proc.

5. Calling a block that has been converted to an object is done with the help of the call method.

ruby-1.9.2-p180 :093 > object.call
hello
 => nil

5. There are other methods that basically convert the block to an object and return the object yo you. They are lamda and Proc.new

ruby-1.9.2-p180 :095 > object1 = lambda {puts "hello"}
#<Proc:0x0000010b193208@(irb):24 (lambda)>

ruby-1.9.2-p180 :096 > object1.call
hello
 => nil
ruby-1.9.2-p180 :097 > object1.class
 => Proc

ruby-1.9.2-p180 :100 > object2 = Proc.new {puts "hello"}
#<Proc:0x0000010b1a8e50@(irb):25>

ruby-1.9.2-p180 :101 > object2.call
hello
 => nil
ruby-1.9.2-p180 :102 > object2.class
 => Proc

7. However there is some difference between lamda and Proc.new. Ruby books talks about it in the advanced sections.
These might also be talking about the same issue
http://stackoverflow.com/questions/626/when-to-use-lambda-when-to-use-proc-new
http://stackoverflow.com/questions/1740046/whats-the-difference-between-a-proc-and-a-lambda-in-ruby

http://samdanielson.com/2007/3/19/proc-new-vs-lambda-in-ruby

Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: