So the last real lesson in the book was on blocks and procedures. Procedures are a lot like methods in that they kind of do the same thing. For example:
def ice_cream excited
'I looooove ice cream! ' * excited
end
puts ice_cream(3)
'I looooove ice cream! ' * excited
end
puts ice_cream(3)
This method just writes the above statement (which is true!) as many times as it's called. That is, compared to a proc:
ice_cream = Proc.new do |i|
puts 'I loooooove ice cream! ' * i
end
ice_cream.call(2)
puts 'I loooooove ice cream! ' * i
end
ice_cream.call(2)
This proc does the exact same thing in a different way! This must be what Pine means by "Tim Toady."
The main difference is that for the proc, we call the code in the proc (between do and end) a block. Blocks and procs... clever right? How's that for assonance?
Procs are useful for two main reasons:
1. You can pass procs into methods (you can't pass methods into methods)
2. Methods can return procs (methods can't return methods)
Apparently you can even pass blocks into methods, but that's all sorts of ridiculous. Is it useful? Pine wrote us a proc that determines how long it takes to do a program. So, I'm going to use that to see how long it took my bubble sorter (and shuffler) to sort or shuffle 100 items in an array.
My Bubble sort 100 words: 0.012246 seconds
My Shuffle 100 words: 0.000309 seconds
That's compared to ruby's built in which is...
Ruby Sort 100 words: 1.7e-05 seconds
Ruby Shuffle 100 words: 4.0e-06 seconds
Then I upped it to 1000 words to see if it made a difference.
My Bubble sort 1000 words: 0.987385 seconds
My Shuffle 1000 words: 0.001996 seconds
Ruby Sort 1000 words: 0.000118 seconds
Ruby Shuffle 1000 words: 4.3e-05 seconds
Good to know that Ruby knows what it is doing better than I do. Goodnight, everybody.
No comments:
Post a Comment