[英]Undefined method for class in Ruby
I'm creating a class. 我正在创建一个课程。 I'm pulling data from a hash named
ROLL_CALL
. 我正在从名为
ROLL_CALL
的哈希中提取数据。 The all
method should return an array of Team
objects. all
方法应返回一个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
When I try to call Team.all
, I get the undefined method for all
. 当我尝试调用
Team.all
,我得到了all
的未定义方法。
Your code isn't structured correctly. 您的代码结构不正确。 That
def all
should be at the top-level and declared as a class-style method. 该
def all
应该在顶层,并声明为类样式方法。 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. 使用
map
而不是创建一个临时数组,并将each
数组中的内容塞入其中,最后只将其返回,因为map
正是为您执行的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.