将对象添加到已初始化的@array
Adding object to initialized @array
我正在尝试创建一个 Country 对象数组。我检查了代码的每一部分,到目前为止,唯一不起作用的是将 Country 对象实际添加到数组中。
谁能帮我理解为什么
array << object
不起作用?完整的代码可以在这里找到http://pastebin.com/jNyJvS3c,有问题的部分在第 23 行。
在代码 country.nil? {@countries << country};
中,{...}
中的代码被视为块且未被执行。以下是更正
以下是建议更正的函数:
def add_country(country)
@countries << country unless country.nil?
end
def to_s(n)
string = ""
for i in 0..n do
string << @countries[i].to_s unless @countries[i].nil?
end
return string
end
在第 23 行中,您实际上将一个块传递给 nil?方法。这个块 {@countries << country} 从来没有被称为 nil 方法?不期望块。
所以做你需要的正确方法:
def add_country(country)
@countries << country unless country.nil?
end
我正在尝试创建一个 Country 对象数组。我检查了代码的每一部分,到目前为止,唯一不起作用的是将 Country 对象实际添加到数组中。
谁能帮我理解为什么
array << object
不起作用?完整的代码可以在这里找到http://pastebin.com/jNyJvS3c,有问题的部分在第 23 行。
在代码 country.nil? {@countries << country};
中,{...}
中的代码被视为块且未被执行。以下是更正
以下是建议更正的函数:
def add_country(country)
@countries << country unless country.nil?
end
def to_s(n)
string = ""
for i in 0..n do
string << @countries[i].to_s unless @countries[i].nil?
end
return string
end
在第 23 行中,您实际上将一个块传递给 nil?方法。这个块 {@countries << country} 从来没有被称为 nil 方法?不期望块。
所以做你需要的正确方法:
def add_country(country)
@countries << country unless country.nil?
end