Last active
January 3, 2018 04:58
-
-
Save topher6345/a4dcdd6058024f5d27432db85767bb60 to your computer and use it in GitHub Desktop.
Ruby Procs and Lamdas
This file contains hidden or 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
l = -> { return :hi_from_lamda } | |
pr = proc { return :hi_from_proc } | |
def foo | |
yield if block_given? | |
return :hi_from_method | |
end | |
# foo :hi_from_method | |
# foo(&l) # :hi_from_method | |
# foo { :hi_from_block } # :hi_from_method | |
# foo(&pr) # :hi_from_proc | |
# foo { return :hi_from_block } :hi_from_block | |
def bar(&block) | |
block.call | |
return :hi_from_method | |
end | |
# bar(&l) :hi_from_method | |
# bar { :hi_from_block } :hi_from_method | |
# bar(&pr) :hi_from_proc | |
# foo { return :hi_from_block } :hi_from_block | |
def baz(block) | |
block.call | |
return :hi_from_method | |
end | |
class Baz | |
def call | |
return :hi_from_baz | |
end | |
end | |
# baz(l) :hi_from_method | |
# baz(pr) :hi_from_proc | |
# baz(Baz.new) :hi_from_method | |
# Lamdas have a special syntax because their idea of return is like any other object | |
# Lamdas are anonymous, 1 method objects | |
# Everything is an object | |
# Lamdas have almost no surface area | |
# RUBY_VERSION 2.4.1 | |
# -> {}.methods.count 76 | |
# Object.methods.count 115 | |
# Hash.methods.count 117 | |
# Think about Object oriented code that doesn't use polymorphism | |
# Service Objects | |
# Lamdas are a great API for Service Objects | |
ll = -> {} | |
ll.call | |
ll.() # great for CreateEnterpriseUser.() | |
ll[] # Most hax - implies some level of predictable access | |
# Partial Evaluation with #curry | |
# allows you to get back that initializer you miss | |
require 'open-uri' | |
adder = -> x, y { open(x).read.chars.count + y } | |
c = adder.curry['https://rubygems.org'] | |
# c[2] 11170 | |
# c[4] 11172 | |
# Somewhat congruent to the below | |
class Faz | |
require 'open-uri' | |
def initialize(x) | |
@count = open(x).read.chars.count | |
end | |
def call(x) | |
@count + x | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment