Created
February 10, 2012 20:15
-
-
Save davetron5000/1792415 to your computer and use it in GitHub Desktop.
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 doit(some_arg) | |
yield some_arg + 10 | |
end | |
# this has the same effect as doit above | |
def doit_explicitly(some_arg,&block) | |
block.call(some_arg + 10) | |
end | |
# we could use the do..end form here if we wanted | |
doit "foo" { |my_arg| | |
# my_arg is some_arg + 10 | |
} | |
# we could use the {} form if we wanted | |
doit_explicitly "foo" do |my_arg| | |
# my_arg is some_arg + 10 | |
end | |
# now we make an explicit block via lambda | |
some_block = lambda { |my_arg| | |
# my_arg will be some_arg + 10 when the code below is executed | |
} | |
doit("foo",&some_block) | |
doit_explicitly("foo",&some_block) | |
# or a proc | |
some_block = proc { |my_arg| | |
# my_arg will be some_arg + 10 when the code below is executed | |
} | |
doit("foo",&some_block) | |
doit_explicitly("foo",&some_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
class Block | |
def call(*args) | |
raise "subclass implement" | |
end | |
end | |
class BlockUser | |
def do_something(a_block) | |
a_block.call("some","arguments","here") | |
end | |
end | |
class PrintEmOutBlock < Block | |
def call(*args) | |
puts args.join(',') | |
end | |
end | |
block_user = BlockUser.new | |
print_block = PrintEmOutBlock.new | |
block_user.do_something(print_block) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment