如何解决如何遍历数组并按关键字存储到新数组中
我目前有一种方法可以从网站上抓取数据并将该信息存储在一个数组中,以便稍后通过其索引(随机给用户)随机调用。我想更进一步,遍历这个数组并创建新数组,其中数据由特定关键字存储,用户可以在其中指定他们是否想要有关树木、花卉或食物的事实。
我该如何编码?我需要创建一个新类吗?或方法?我是否需要定义要在另一种方法中调用的数组名称以再次迭代?有什么有效的方法可以做到这一点。
我当前存储在数组中的刮刀是
def facts
array=[]
doc = Nokogiri::HTML(URI.open("https://www.funfactsabout.net/plant-facts/"))
doc.css("ul.facts-list li").each do |list|
array.push(list.text)
end
return array
end
然后我在课堂上的方法之一是
def more
input_prompt = "\n\n Enter a number between 1-42 for a random plant fact,or type 'leave' to exit: \n\n"
input = nil
while true
puts input_prompt
input = gets.strip
if input.to_i > 0 && input.to_i < facts.length + 1
puts facts[input.to_i - 1]
elsif input == "leave"
puts goodbye
return
else
puts "Sorry,I didn't understand that."
end
end
end
解决方法
我会为此创建一个类,例如
class RandomFacts
attr_reader :name
def initialize(name)
@name = name
end
def to_a
document.css("ul.facts-list li").map do |list|
list.text
end
end
private
def document
Nokogiri::HTML(url)
end
def url
URI.open("https://www.funfactsabout.net/#{name}-facts/")
end
end
在类中,您根据这样的事实名称构造 URL
RandomFacts.new("plant").to_a
RandomFacts.new("science").to_a
然后您必须提示用户有关事实和数字,并且可以生成例如像一个哈希
facts = {
"science" => RandomFacts.new("science").to_a,"plant" => RandomFacts.new("plant").to_a
}
facts["plant"][1]
facts["science"][42]