Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Ruby Modules Ruby Core Modules Enumerable

Mark Weinberg
Mark Weinberg
3,002 Points

Define an each method on the Game class that accepts a block and sends that block to the players array.

i am on Challenge 2 of 2 for "Define an each method on the Game class that accepts a block and sends that block to the players array." Can someone show me the correct code so I know what I'm doing wrong?

Sincerely,

Mark Weinberg

player.rb
class Player
  include Comparable
  attr_accessor :name, :score

  def <=>(other)
    score <=> other.score
  end

  def initialize(name, score)
    @name = name
    @score = score
  end
end

class Game
  include Enumerable
  attr_accessor :players

  def initialize
    @players = []
  end
end

2 Answers

Grace Kelly
Grace Kelly
33,990 Points

Hi Mark, the challenge asks us to define an each method within the Game class that accepts a block. This block then needs to be passed into the players array, we do this in the following way:

 def each(&block) #define the each function that accepts a block
    players.each(&block) #pass the block into the players array
  end

Hope that helps!!

Jillian Dunleavy
Jillian Dunleavy
3,685 Points

I had been stuck on this for a little too, so I went back to the video and typed in what Jason had when he was doing an each method on the game class. It's the video right before this objective and the part that I was using started at around 5:40. Starting in the attr_accessor in the game class, this is my code that passed.

attr_accessor :players

def each(&block) players.each(&block) end

def initialize

the rest of the code that is already written out from the previous task...