简体   繁体   中英

Undefined method for class in Ruby

I'm creating a class. I'm pulling data from a hash named ROLL_CALL . The all method should return an array of Team objects.

require_relative "./team_data"
class Team
  attr_reader :name
  def intialize (name)
    @name = name
    def all
      all_teams = []
      TeamData::ROLL_CALL.each do |team, info|
        all_teams << Team.new(team)
      end
      all_teams
    end
  end
end

When I try to call Team.all , I get the undefined method for all .

Your code isn't structured correctly. That def all should be at the top-level and declared as a class-style method. There's also some other things worth fixing:

require_relative "./team_data"

class Team
  def self.all
    TeamData::ROLL_CALL.map do |team, info|
      Team.new(team)
    end
  end

  attr_reader :name

  def intialize (name)
    @name = name
  end
end

Use map instead of creating a temporary array and jamming things into it with each only to return it in the end, as that's exactly what map does for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM