如何在两个相似的数组上同时迭代每个_value

时间:2022-06-06 11:45:52

In this case, both locales and aliases share the same structure and so I iterate them in the same way changing only its name.

在本例中,locales和aliases共享相同的结构,所以我以相同的方式迭代它们,只更改它的名称。

if yml_site['locales'].present? 
     yml_site['locales'].each_value do |yml_locale|
          site = Site.find_or_create_by_domain(
               locale: yml_locale['locale'],
               domain: yml_locale['domain'],
               title: yml_locale['title'],
               parent: yml_site['domain'],
     end
end
if  yml_site['aliases'].present?
     yml_site['aliases'].each_value do |yml_alias|
          site = Site.find_or_create_by_domain(
               locale: yml_alias['locale'],
               domain: yml_alias['domain'],
               title: yml_alias['title'],
               parent: yml_alias['domain'],
     end
end
end

I was thinking to simplify this code with something like [yml_site['locales'],yml_site['aliases']].each.each_value but obviusly its not working. Any idea how can I iterate both yml_site['locales'] and yml_site['aliases'] on the same query ?

我想用类似于[yml_site['locales'],yml_site['aliases']]这样的东西来简化这段代码。每个值,但显然它不工作。知道我如何在同一个查询中迭代yml_site['locales']和yml_site['aliases']吗?

2 个解决方案

#1


5  

How about this:

这个怎么样:

(yml_site['locales'] + yml_site['aliases']).each_value do |yml_locale|
  ...
end

#2


1  

Simple way is to push the iteration block to a common method and access it by method calls.

简单的方法是将迭代块推到一个通用方法,并通过方法调用访问它。

Other alternative, Just perform array addition,

另一种选择,只是执行数组加法,

x1 = [1,2,3]
x2 = [3,4,5]

x1 + x2, and then perform iteration as done for array.

To execute the operation in parallel, you can use

要并行执行操作,可以使用

x1.zip(x2).each do |u,v|
  p u
  p v
  #perform find_or_create operation
end

#1


5  

How about this:

这个怎么样:

(yml_site['locales'] + yml_site['aliases']).each_value do |yml_locale|
  ...
end

#2


1  

Simple way is to push the iteration block to a common method and access it by method calls.

简单的方法是将迭代块推到一个通用方法,并通过方法调用访问它。

Other alternative, Just perform array addition,

另一种选择,只是执行数组加法,

x1 = [1,2,3]
x2 = [3,4,5]

x1 + x2, and then perform iteration as done for array.

To execute the operation in parallel, you can use

要并行执行操作,可以使用

x1.zip(x2).each do |u,v|
  p u
  p v
  #perform find_or_create operation
end