Kamilski81
Kamilski81

Reputation: 15107

How can I make a cleaner append in ruby?

I have the following code, and I just want to make it look cleaner, any suggestions? Basically, a team has many games, and I want to merge all the games and order them by their attribute game.game_date??

    @games = Array.new
    @teams.each {|team|
      team_games = team.games
      @games << team_games
    }

    @games = @games.flatten

Upvotes: 1

Views: 77

Answers (2)

Mike Tunnicliffe
Mike Tunnicliffe

Reputation: 10762

How about:

@teams.map(&:games).flatten.sort_by(&:game_date)

...or maybe:

@teams.reduce([]) { |memo, team| memo + team.games }.sort_by(&:game_date)

...this can be written as follows on recent Ruby versions (not sure exactly when this came in):

@teams.reduce([], :+).sort_by(&:game_date)

NB: Symbol#to_proc (the bits that look like &:symbol) needs a recent version of Ruby (not quite sure of the required version). This construct is the same as passing a block like { |arg| arg.symbol } to the method. Eg: map(&:games) is equivalent to map { |team| team.games }

NB the second: collect and map are synonyms, as are inject and reduce.

Upvotes: 4

bloudermilk
bloudermilk

Reputation: 18109

How about this?

@games = @teams.map(&:games).flatten

Upvotes: 0

Related Questions