Ruby on rails 将数组元素减少为嵌套类实例化
假设我有以下数组:Ruby on rails 将数组元素减少为嵌套类实例化,ruby-on-rails,ruby,Ruby On Rails,Ruby,假设我有以下数组: operations = [ [ :do_this, ["a"] ], [ :do_that, ["b", "c"] ], [ :then_this, ["b"] ] ] 如何在上面进行变换,使其看起来像: DoThisOperation.new(DoThatOperation.new(ThenThisOperation.n
operations = [
[
:do_this,
["a"]
],
[
:do_that,
["b", "c"]
],
[
:then_this,
["b"]
]
]
如何在上面进行变换,使其看起来像:
DoThisOperation.new(DoThatOperation.new(ThenThisOperation.new('b'), 'b' , 'c'), 'a')
就我所知:
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
减少/注入是正确的方法吗?如果是,我应该在上面做什么
减少/注入是正确的方法吗
可以,但您需要将初始值传递给reduce
,例如nil
。否则,第一个元素(在本例中是最后一个元素)将用作初始值,而不进行转换
这将有助于:
operations.reverse.reduce(nil) do |result, element|
klass_name = element[0].to_s.camelize
args = element[1]
"#{klass_name}Operation".constantize.new(result, *args)
end
您可以使用数组分解进一步简化它:
operations.reverse.reduce(nil) do |result, (name, args)|
klass_name = name.to_s.camelize
"#{klass_name}Operation".constantize.new(result, *args)
end
甚至:
operations.reverse.reduce(nil) do |result, (name, args)|
"#{name}_operation".camelize.constantize.new(result, *args)
end
减少/注入是正确的方法吗
可以,但您需要将初始值传递给reduce
,例如nil
。否则,第一个元素(在本例中是最后一个元素)将用作初始值,而不进行转换
这将有助于:
operations.reverse.reduce(nil) do |result, element|
klass_name = element[0].to_s.camelize
args = element[1]
"#{klass_name}Operation".constantize.new(result, *args)
end
您可以使用数组分解进一步简化它:
operations.reverse.reduce(nil) do |result, (name, args)|
klass_name = name.to_s.camelize
"#{klass_name}Operation".constantize.new(result, *args)
end
甚至:
operations.reverse.reduce(nil) do |result, (name, args)|
"#{name}_operation".camelize.constantize.new(result, *args)
end
我不明白为什么你有
then\u this(a)
,它看起来更像do\u this(b,b,c),a)
?reduce代码应该是:operations.reverse.reduce(nil)do | result,element |…
,你错过了nil
作为初始值。顺便说一下,您需要然后此操作
映射为a
,它应该映射为b
,对吗?或者这就是你想要的,参数的顺序是相反的?@muistooshort你是对的。让我来编辑一下expectation@LamPhan你是对的。使用nil
(即reduce(nil)
),它可以按预期工作!谢谢你。如果你把它作为一个答案,我会很高兴地把它标记为suchI不明白为什么你有,那么这个(a)
,它看起来会不会更像做这个(做那)(那么这个(b),b,c),a)
?reduce代码应该是:操作。reverse.reduce(nil)do | result,element |…
,你错过了nil
。顺便说一下,您需要然后此操作
映射为a
,它应该映射为b
,对吗?或者这就是你想要的,参数的顺序是相反的?@muistooshort你是对的。让我来编辑一下expectation@LamPhan你是对的。使用nil
(即reduce(nil)
),它可以按预期工作!谢谢你。如果你把它作为一个答案,我会很高兴地把它标记为数组分解部分非常好的提示数组分解部分非常好的提示