Pregunta

I'm trying to understand why this code works. Specifically,

1.In the method definition for compose, why do you have to create a new Proc? Why can't you call proc2 and proc1 without creating a new proc?

2.I tried creating the function 'double_then_square' but it only works as an assignment. Is that the case because you can't have methods within methods? Wouldn't recursion be a counterexample of that though or is the rule that you can't have different methods within methods?

def compose(proc1, proc2)
    Proc.new do |x|
        proc2.call(proc1.call(x))
    end
end

square_it = Proc.new do |n|
    n ** 2
end

double_it = Proc.new do |n|
    n * 2
end


double_then_square = compose(double_it,square_it)
puts double_then_square.call(1)
¿Fue útil?

Solución

  1. Because that would execute this immediately when you define double_then_square, clearly not possible since we don't know that 1 is getting passed in yet. Instead, you want something you can call, e.g., send a .call(1) on. That is, we want to return a Proc.

  2. No, it should be doable. However, you will not be able to access your local variables, so you will have to define them in the method instead. Since it is a proper method, you will also call it directly instead of using .call. The code below works for me.


def double_then_square(*args)
  square_it = Proc.new do |n|
    n ** 2
  end

  double_it = Proc.new do |n|
    n * 2
  end
  compose(double_it,square_it).call(*args)
end
double_then_square(1)
# 4
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top