Skip to content

Instantly share code, notes, and snippets.

@kjlape
Created September 1, 2020 16:45
Show Gist options
  • Save kjlape/2a687e095628ef51927eef2b9734a928 to your computer and use it in GitHub Desktop.
Save kjlape/2a687e095628ef51927eef2b9734a928 to your computer and use it in GitHub Desktop.
Playing with functional composition in ruby.
if Gem::Version.new("2.6") <= Gem::Version.new(RUBY_VERSION)
def compose(*funcs)
funcs.map(&:to_proc).reduce(:<<)
end
else
def compose(*funcs)
funcs.map(&:to_proc).reduce { |f, g| ->(*x) { f.call(g.call(*x)) } }
end
end
def a(x)
"a(#{x})"
end
def b(x)
"b(#{x})"
end
def c(x)
"c(#{x})"
end
results = %w[functional programming].map(&compose(method(:a), method(:b), method(:c)))
expected = ["a(b(c(functional)))", "a(b(c(programming)))"]
raise "unexpected results! 😵\nactual: #{results}\nexpected: #{expected}" unless results == expected
puts "✅ #{results}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment