Given I have the following array:
operations = [
[
:do_this,
["a"]
],
[
:do_that,
["b", "c"]
],
[
:then_this,
["b"]
]
]
How do I transform above so it looks like:
DoThisOperation.new(DoThatOperation.new(ThenThisOperation.new('b'), 'b' , 'c'), 'a')
This is as far as I've gotten:
require 'active_support/inflector'
class DoThisOperation
def initialize(successor = nil, a)
end
end
class DoThatOperation
def initialize(successor = nil, b, c)
end
end
class ThenThisOperation
def initialize(successor = nil, b)
end
end
operations = [
[
:do_this,
["a"]
],x
[
:do_that,
["b", "c"]
],
[
:then_this,
["b"]
]
]
operations.reverse.reduce do |result, element|
klass_name = element[0].to_s.camelize
args = element[1]
"#{klass_name}Operation".constantize.new(result, *args)
end
Is reduce/inject the right way to go about this? If so, what should I be doing above?
operations.reverse.reduce(nil) do |result, element| ..., you missnilas initial value. By the way, your require thatThenThisOperationmap witha, it shoule be map withb, right ? Or that is what you want, the params will be in inverse order ?nil(i.e.reduce(nil)), it works as expected! Thank you for that. If you leave it as an answer, I will gladly mark it as such