Skip to content

Instantly share code, notes, and snippets.

@koriroys
Created March 29, 2012 20:36
Show Gist options
  • Save koriroys/2243533 to your computer and use it in GitHub Desktop.
Save koriroys/2243533 to your computer and use it in GitHub Desktop.
Why do the last two lines work?
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]
@koriroys
Copy link
Author

Taken from http://pine.fm/LearnToProgram/?Chapter=10 "Methods Which Return Procs"

Why do the last two lines work? Befuddled, I am.

@JoshCheek
Copy link

Proc#[] is an alias of Proc#call docs

@JoshCheek
Copy link

p = Proc.new { |n| n**2 }
p.call(5) # => 25
p[5]      # => 25

@thegrubbsian
Copy link

Yeah, what josh said ;)

@koriroys
Copy link
Author

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