我该如何排序这个数组?

时间:2012-03-08 10:32:26

标签: ruby arrays sorting

我有一个数组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 gem,它提供了一个方法#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] }

但我不知道该想要怎么做。

2 个答案:

答案 0 :(得分: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"]

答案 1 :(得分:0)

所以我已经弄清楚了:

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

这不是100%有效,但这是宝石所依赖的词典的错误。