Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何将阵列中的多个对象铲到一个对象中?_Ruby_Refactoring - Fatal编程技术网

Ruby 如何将阵列中的多个对象铲到一个对象中?

Ruby 如何将阵列中的多个对象铲到一个对象中?,ruby,refactoring,Ruby,Refactoring,我有一个团队课程: class Team attr_accessor :teamplayers def initialize @team_players = [] end def <<(player) @team_players << player end def to_s puts "THIS IS THE TEAM #{@team_players}" end end 班级团队 属性访问器:团队成员 def初始

我有一个
团队
课程:

class Team
  attr_accessor :teamplayers
  def initialize
    @team_players = []
  end
  def <<(player)  
    @team_players << player
  end
  def to_s
    puts "THIS IS THE TEAM #{@team_players}" 
  end
end
班级团队
属性访问器:团队成员
def初始化
@团队成员=[]
结束
def
您还可以在每次添加内容时展平阵列:

def <<(player)
  @team_players << player
  @team_players.flatten!
end
def t[“鲍勃”、“爱丽丝”、“乔”、“比尔”]

剩下的问题是,您是否希望通过隐式转换将
的方式缩短一点:

def <<(*player)
   @team_players.concat player.flatten
end
def只需使用
+
(或
concat
):


问题是什么?您是否遇到了一个错误,因为您的代码似乎会按照标题的建议执行。
def <<(player)
  if player.kind_of?(Array)
    @team_players.concat player  
  else
    @team_players << player
  end
end
def <<(player)
  @team_players << player
  @team_players.flatten!
end
irb(main):032:0> t << ["Bob"]
=> ["Bob"]
irb(main):032:0> t << ["Alice", "Joe"]
=> ["Bob", "Alice", "Joe"]
irb(main):033:0> t << ["Bill"]
=> ["Bob", "Alice", "Joe", "Bill"]
def <<(*player)
   @team_players.concat player.flatten
end
team = team + @defenders[-1..-4]
#or 
team.concat(@defenders[-1..-4])