Ruby 中 class 的未定义方法
Undefined method for class in Ruby
我正在创建 class。我正在从名为 ROLL_CALL
的哈希中提取数据。 all
方法应该 return 一个包含 Team
个对象的数组。
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
当我尝试调用 Team.all
时,我得到了 all
的未定义方法。
您的代码结构不正确。 def all
应该在顶层并声明为 class 风格的方法。还有一些其他值得修复的东西:
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
使用 map
而不是创建一个临时数组,然后用 each
将内容塞入其中,直到最后 return 它,因为这正是 map
所做的给你。
我正在创建 class。我正在从名为 ROLL_CALL
的哈希中提取数据。 all
方法应该 return 一个包含 Team
个对象的数组。
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
当我尝试调用 Team.all
时,我得到了 all
的未定义方法。
您的代码结构不正确。 def all
应该在顶层并声明为 class 风格的方法。还有一些其他值得修复的东西:
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
使用 map
而不是创建一个临时数组,然后用 each
将内容塞入其中,直到最后 return 它,因为这正是 map
所做的给你。