Created
May 17, 2010 08:58
-
-
Save louis-wu/403544 to your computer and use it in GitHub Desktop.
Proc and Block
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#--- | |
# Ruby Facts: Proc and Block | |
#--- | |
#take a block of code (code in between do and end), | |
#wrap it up in an object (called a proc), | |
# store it in a variable or pass it to a method, | |
#and run the code in the block whenever you feel like it | |
>> toast = Proc.new do | |
?> puts "cheers!" | |
>> end | |
=> #<Proc:0x7fe5a61c@(irb):4> | |
>> toast.call | |
cheers! | |
#blocks can take parameters | |
>> do_you_like = Proc.new do |good_stuff| | |
?> puts "I like #{good_stuff}!" | |
>> end | |
=> #<Proc:0x7fe54438@(irb):8> | |
>> do_you_like.call "Ruby" | |
I like Ruby! | |
#Methods That Take Procs | |
def twice_do some_proc | |
>> some_proc.call | |
>> some_proc.call | |
>> end | |
=> nil | |
>> wink = Proc.new do | |
?> puts "wink" | |
>> end | |
=> #<Proc:0x7fe50004@(irb):15> | |
>> twice_do wink | |
wink | |
wink | |
#Passing Blocks (Not Procs) into Methods | |
#In order to make your method grab the block and turn the block into a proc, | |
#put the name of the proc at the end of your method’s parameter list, | |
#preceded by an ampersand (&). | |
>> def profile block_description, &block | |
>> start_time = Time.new | |
>> block.call | |
>> duration = Time.new - start_time | |
>> puts "#{block_description}: #{duration} seconds" | |
>> end | |
>> profile 'count to a million' do | |
?> number = 0 | |
>> 1000000.times do | |
?> number = number + 1 | |
>> end | |
>> end | |
count to a million: 0.41 seconds |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Proc: you can store it or pass it around like you can with any object