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])