Faery
Faery

Reputation: 4650

Accessing methods in a Ruby block

I have a block which is passed as argument to a function. This block contains several methods. It's like this:

def func(&block)
end

func do
  method1
  method2(arg)
  method3(arg)
end

I want func to return the composition of the functions in the block:

method3 ( method2 ( method1 ) )

Is there a way to have access to each of the methods in the block, so I can use methods.reduce(method1) { |method| method.call arg } or something like this?

Can you please give me some ideas?

Upvotes: 1

Views: 194

Answers (1)

Simone Carletti
Simone Carletti

Reputation: 176552

No, this is not possible. You could (in theory) parse the Ruby code associated to the block definition, but I'm not sure that would make sense.

Your question is very generic, you don't provide any detail if you have control over the block or not, and a real world example would probably be more helpful.

From the details I have, my suggestion is that you should split the block at the origin. Instead of passing the whole block containing all those methods, pass an array of the methods as argument so that you can reuse them as you want.

You can wrap them in a lambda, to delay the execution.

def func(*chain)
end

func(
  ->(arg) { method1 },
  ->(arg) { method2(arg) },
  ->(arg) { method3(arg) }
)

You can also use Object.method to fetch the method and pass it as parameter.

def func(*chain)
end

func(
  method(:method1),
  method(:method2),
  method(:method3)
)

Upvotes: 3

Related Questions