【发布时间】:2016-12-18 22:30:06
【问题描述】:
我正在尝试为数组中的每个单词搜索一个段落,然后输出一个新数组,其中仅包含可以找到的单词。
但到目前为止,我一直无法获得所需的输出格式。
paragraph = "Japan is a stratovolcanic archipelago of 6,852 islands.
The four largest are Honshu, Hokkaido, Kyushu and Shikoku, which make up about ninety-seven percent of Japan's land area.
The country is divided into 47 prefectures in eight regions."
words_to_find = %w[ Japan archipelago fishing country ]
words_found = []
words_to_find.each do |w|
paragraph.match(/#{w}/) ? words_found << w : nil
end
puts words_found
目前我得到的输出是打印单词的垂直列表。
Japan
archipelago
country
但我想要['Japan', 'archipelago', 'country']。
我没有太多在段落中匹配文本的经验,并且不确定我在这里做错了什么。谁能给点指导?
【问题讨论】:
-
words_found已经是你想要的了。puts每行打印一个元素。 -
啊,谢谢。我需要阅读
puts与p -
P.S.你可以
p words_found看看它到底是什么。