Ruby 获取句子中最长的单词 [英] Ruby getting the longest word of a sentence

查看:36
本文介绍了Ruby 获取句子中最长的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建名为 longest_word 的方法,该方法将句子作为参数,该函数将返回句子中最长的单词.

I'm trying to create method named longest_word that takes a sentence as an argument and The function will return the longest word of the sentence.

我的代码是:

def longest_word(str)
  words = str.split(' ')
  longest_str = []
  return longest_str.max
end

推荐答案

这取决于您想如何拆分字符串.如果您对使用单个空间感到满意,则可以这样做:

It depends on how you want to split the string. If you are happy with using a single space, than this works:

def longest(source)
  arr = source.split(" ")
  arr.sort! { |a, b| b.length <=> a.length }
  arr[0]
end

否则,请使用正则表达式来捕获空格和标点符号.

Otherwise, use a regular expression to catch whitespace and puntuaction.

这篇关于Ruby 获取句子中最长的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆