Skip to content

Instantly share code, notes, and snippets.

@qxjit
Created June 27, 2014 21:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qxjit/08038faf810c0f5857e7 to your computer and use it in GitHub Desktop.
Save qxjit/08038faf810c0f5857e7 to your computer and use it in GitHub Desktop.
Ruby proc & symbol composition
def comp(*gs)
id = -> x { x }
gs.inject(id) do |f,g|
-> x do
f.to_proc.call g.to_proc.call x
end
end
end
times_2 = -> x { x * 2 }
plus_3 = -> x { x + 3 }
puts comp(times_2, plus_3).call(1) #=> 8
puts comp(plus_3, times_2).call(1) #=> 5
p (9..12).map(&comp(:reverse, :to_s)) #=> ["9", "01", "11", "21"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment