I have a Team class:
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
I want to add members to the team with <<. I use this code:
team << @goalkeepers.last
team << @defenders[-1..-4]
team << @midfielders[-1]
team << @attackers[-1..-2]
The first line works fine and adds one member to the team. The other lines however add arrays to my team, not the actual members.
How can I add the members individually then?
team << @defenders[-1..-4]
You're adding an array (@defenders[-1..-4]) inside another array. Naturally, the actual element added will be the whole array, and Ruby doesn't flatten it for you automatically.
If you don't want it to do that, you could concatenate the elements in the << method if they're an array:
def <<(player)
if player.kind_of?(Array)
@team_players.concat player
else
@team_players << player
end
end
You could also flatten the array every time you added something:
def <<(player)
@team_players << player
@team_players.flatten!
end
This would then work with single objects and arrays. For example:
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"]
The remaining question is whether you want to override the way << typically works and if it wouldn't be a better idea to do @defenders[-1..-4].each { |d| team << d }.
A bit shorter with a implicit conversion:
def <<(*player)
@team_players.concat player.flatten
end
Stay with slhck answer, haven't seen the flatten variation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With