从字符串中提取的最大和最小单词

时间:2013-04-23 12:51:48

标签: ruby

我的字符串为 "Frederik will not come office tomorrow.So please you have to do his tasks". 我想要最小和最大长度的单词作为哈希,如下所示:

{2=>["So", "to", "do"], 8=>["Frederik", "tomorrow"]}

那么最简单的做法是什么?

1 个答案:

答案 0 :(得分:8)

尝试以下方法:

w = "Frederik will not come office tomorrow.So please you have to do his tasks" 
p Hash[w.scan(/\w+/).group_by(&:length).minmax]

#=>{2=>["So", "to", "do"], 8=>["Frederik", "tomorrow"]}