I'm trying to learn Ruby right now after learning Python and I'm having trouble translating this code to Ruby:
def compose1(f, g):
"""Return a function h, such that h(x) = f(g(x))."""
def h(x):
return f(g(x))
return h
Do I have to translate this using blocks? Or is there a similar syntax in Ruby?
You can do this with lambdas in Ruby (I'm using the 1.9 stabby-lambda here):
compose = ->(f,g) {
->(x){ f.(g.(x)) }
}
So compose
is a function that returns another function, as in your example:
f = ->(x) { x + 1 }
g = ->(x) { x * 3 }
h = compose.(f,g)
h.(5) #=> 16
Note that functional programming is not really Ruby's strong suit - it can be done but it looks a bit messy in my opinion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With