Created
March 29, 2012 20:36
-
-
Save koriroys/2243533 to your computer and use it in GitHub Desktop.
Why do the last two lines work?
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
def compose proc1, proc2 | |
Proc.new do |x| | |
proc2.call(proc1.call(x)) | |
end | |
end | |
squareIt = Proc.new do |x| | |
x**2 | |
end | |
doubleIt = Proc.new do |x| | |
x + x | |
end | |
squareThenDouble = compose squareIt, doubleIt | |
doubleThenSquare = compose doubleIt, squareIt | |
puts squareThenDouble.call(5) | |
puts doubleThenSquare.call(5) | |
puts squareThenDouble[5] | |
puts doubleThenSquare[5] |
Proc#[]
is an alias of Proc#call
docs
p = Proc.new { |n| n**2 }
p.call(5) # => 25
p[5] # => 25
Yeah, what josh said ;)
Ah ha. Thanks dudes, that makes sense.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Taken from http://pine.fm/LearnToProgram/?Chapter=10 "Methods Which Return Procs"
Why do the last two lines work? Befuddled, I am.