配对红宝石中的数组元素

时间:2010-07-03 08:51:09

标签: ruby arrays

假设我有一个名为teams的数组 我希望为每个matches计划team与其他team。{/ p>

这几乎是我想要的,除了相同的matches被添加两次:

teams.each do |red_team|
  teams.each do |blue_team|
    if red_team != blue_team
      @planned_matches << Match.new(red_team, blue_team)
    end
  end
end

怎么做?

3 个答案:

答案 0 :(得分:8)

在Ruby 1.8.7+中,您可以使用Array#combination

teams = %w(A B C D)
matches = teams.combination(2).to_a

在1.8.6中,您可以使用Facets执行相同的操作:

require 'facets/array/combination'
# Same code as above.

答案 1 :(得分:2)

检查它是否有效

for i in 0..teams.length-1
  if i != teams.last
    for j in (i+1)..teams.length-1
      @planned_matches << Match.new(teams[i], teams[j])
    end
  end
end

实施例

teams = ['GERMANY', 'NETHERLAND', 'PARAGUAY', 'ARGENTINA']
for i in 0..teams.length-1
  if i != teams.last
    for j in (i+1)..teams.length-1
      puts " #{teams[i]}  Vs  #{teams[j]}"
    end
  end
end

O / P

 GERMANY  Vs  NETHERLAND
 GERMANY  Vs  PARAGUAY
 GERMANY  Vs  ARGENTINA
 NETHERLAND  Vs  PARAGUAY
 NETHERLAND  Vs  ARGENTINA
 PARAGUAY  Vs  ARGENTINA

答案 2 :(得分:0)

在您的班级匹配中,假设内部属性为redblue

class Match
#...
  def ==(anOther)
    red == anOther.blue and anOther.red == blue
  end
#...
end

和循环:

teams.each do |red_team|
  teams.each do |blue_team|
    if red_team != blue_team
      new_match = Match.new(red_team, blue_team)
      planned_matches << new_match if !planned_matches.include?(new_match)
    end
  end
end

说明:

include? Array函数使用==方法,因此您只需覆盖它并为其提供您想要的匹配行为。