需要嵌套循环来打印ruby中两个数组的值

时间:2017-12-19 12:46:00

标签: ruby-on-rails ruby

我有两个数组

ids = ["10.12.14","10.12.15"]
iq = ["abc","pqr"]

我希望o / p采用以下格式

New-IscsiTargetPortal -TargetPortalAddress 10.12.14
New-IscsiTargetPortal -TargetPortalAddress 10.12.15
Connect-IscsiTarget -NodeAddress abc -TargetPortalAddress 10.12.14 -IsPersistent $True
Connect-IscsiTarget -NodeAddress xyz -TargetPortalAddress 10.12.15 -IsPersistent $True

我的代码看起来像

for i in ids
  for j in iq
    puts "New-IscsiTargetPortal -TargetPortalAddress #{i}"
    puts "Connect-IscsiTarget -NodeAddress #{j} -TargetPortalAddress #{i} -IsPersistent $True"
  end
end

但它重复了i和j的值:

New-IscsiTargetPortal -TargetPortalAddress 10.12.14
Connect-IscsiTarget -NodeAddress abc -TargetPortalAddress 10.12.14 -IsPersistent $True
New-IscsiTargetPortal -TargetPortalAddress 10.12.14
Connect-IscsiTarget -NodeAddress pqr -TargetPortalAddress 10.12.14 -IsPersistent $True
New-IscsiTargetPortal -TargetPortalAddress 10.12.15
Connect-IscsiTarget -NodeAddress abc -TargetPortalAddress 10.12.15 -IsPersistent $True
New-IscsiTargetPortal -TargetPortalAddress 10.12.15
Connect-IscsiTarget -NodeAddress pqr -TargetPortalAddress 10.12.15 -IsPersistent $True

你可以帮我嵌套for循环或我如何得到o / p?

4 个答案:

答案 0 :(得分:1)

▶ result = ids.zip(iq).
▷   flat_map do |ip, name|
▷     ["New #{ip}", "Connect #{name} :: #{ip}"]
▷   end.partition { |s| s.start_with? 'New' }.flatten
#⇒ [
#  [0] "New 10.12.14",
#  [1] "New 10.12.15",
#  [2] "Connect abc :: 10.12.14",
#  [3] "Connect pqr :: 10.12.15"
# ]

▶ result.each(&method(:puts))
New 10.12.14
New 10.12.15
Connect abc :: 10.12.14
Connect pqr :: 10.12.15

答案 1 :(得分:1)

对于第一部分,您可以迭代ids

ids.each do |i|
  puts "New-IscsiTargetPortal -TargetPortalAddress #{i}"
end

对于第二部分,您可以使用Array#zip成对组合idsiq

ids.zip(iq) do |i, j|
  puts "Connect-IscsiTarget -NodeAddress #{j} -TargetPortalAddress #{i} -IsPersistent $True"
end

输出:

New-IscsiTargetPortal -TargetPortalAddress 10.12.14
New-IscsiTargetPortal -TargetPortalAddress 10.12.15
Connect-IscsiTarget -NodeAddress abc -TargetPortalAddress 10.12.14 -IsPersistent $True
Connect-IscsiTarget -NodeAddress pqr -TargetPortalAddress 10.12.15 -IsPersistent $True

答案 2 :(得分:0)

如果您可以依赖于连接的两种数据(即10.12.14>" abc"),那么您可以在处理之前更好地构建数据,以使这更容易:

h = [{
      target: "10.12.14",
      node: "abc"
    },
    {
      target: "10.12.15",
      node: "xyz"
    }]

在此之后,你需要专门为目标地址(数组a)循环一次以获得前两行,然后第二次循环用于组合信息行,这看起来像这样: / p>

for o in h
  puts "New-IscsiTargetPortal -TargetPortalAddress #{o[:target]}"     
end

for o in h
  puts "Connect-IscsiTarget -NodeAddress #{o[:node]} -TargetPortalAddress #{i[:target]} -IsPersistent $True"
end

答案 3 :(得分:0)

使用each_with_index并使用第一个数组的索引来确定在第二个数组上检索哪个元素。

ids.each_with_index do |id, index|
    puts "New-IscsiTargetPortal -TargetPortalAddress #{id}"
    puts "Connect-IscsiTarget -NodeAddress #{iq[index]} -TargetPortalAddress #{id} -IsPersistent $True"
  end
end