Skip to content

Instantly share code, notes, and snippets.

@jwo
Created June 28, 2015 15:41
Show Gist options
  • Save jwo/e89c79868c6ddeaaf7e0 to your computer and use it in GitHub Desktop.
Save jwo/e89c79868c6ddeaaf7e0 to your computer and use it in GitHub Desktop.
procs, lambda, and blocks
require 'active_support/all'
### We can send in a proc (or a lambda) for the method to call when we want it
### to run. the proc behaves like a normal argument
$array = %w(apple banana kumquat)
def titlize_fruits(proc)
proc.call $array.pop
proc.call $array.pop
proc.call $array.pop
end
titlize_fruits(Proc.new {|fruit| puts fruit.titleize})
### We can also send in a block
### * All methods can receive 1 (and only 1) block
### * We yield control to the block
$array = %w(apple banana kumquat)
def upcase_fruits
yield $array.pop
yield $array.pop
yield $array.pop
end
upcase_fruits do |fruit|
puts fruit.upcase
end
### We can also get access to the block and call it directly, like we would a proc
$array = %w(apple banana kumquat)
def hackerize_fruits(&block)
block.call $array.pop
block.call $array.pop
block.call $array.pop
end
hackerize_fruits do |fruit|
# We can also define a lambda as a variable
hack_it = lambda { |c|
if [true,false].sample
c.swapcase
else
c
end
}
# and then send in the lambda to a method like `each`, `map`
puts fruit.chars.map(&hack_it).join("")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment