2012-03-08 71 views
0

我有一个数组,headlines,保存几个句子,所以像:我该如何排序这个数组?

headlines = ["I see a tree", "Facebook is slow", "plants need water to grow", "There's an orange", "I think we'll agree"] 
first = headlines[0] 
second = headlines[1] 
third = headlines[2] 

我使用ruby_rhymes宝石所提供的方法#to_phrase.rhymes打印出押韵的最后一个字的话在你提供一个字符串用。我们检查字符串数组韵,我做这样的事情:

> first.to_phrase.rhymes.flatten.join(", ").include?(second.to_phrase.rhymes.flatten.join(", ")) 
=> false 
> second.to_phrase.rhymes.flatten.join(", ").include?(third.to_phrase.rhymes.flatten.join(", ")) 
=> true 

我希望将这些保存到一个文本文件,所以我想他们在阵列中进行排序,以便押韵对是彼此以后。我知道要排序,所以如果最后3个字符是相同的字符串是:

headlines.sort! {|a,b| a[-3,3] <=> b[-3,3] } 

但我不知道如何去做我想要的。

回答

0

所以我想通了:

headlines.sort_by! { |h| h.to_phrase.rhyme_key } 

这不起作用100%,但是这的故障宝石依赖的字典。

0

通过研究你的建议的输出,你可以看到你在正确的轨道上:

p headlines.sort {|a,b| a[-3,3] <=> b[-3,3] } 
# => ["Facebook is slow", "There's an orange", "I see a tree", "I think we'll agree", "plants need water to grow"] 

“......慢”和“...成长”是唯一的无序的句子,引起字母'r'和'o'。一个简单的黑客将扭转这样的比较顺序:

p headlines.sort {|a,b| a[-3,3].reverse <=> b[-3,3].reverse } 
# => ["I see a tree", "I think we'll agree", "There's an orange", "Facebook is slow", "plants need water to grow"] 
+0

不,这不起作用。如果标题数组获得数百个字符串,那么(和我建议的)方法将无法工作。它不适用于押韵的单词,但拼写方式与'through'和'you'拼写完全不同。 – Simpleton 2012-03-08 12:17:25