首页 > 解决方案 > 如何在字符串中搜索最长的单词

问题描述

  def my_inject(*args)
    return yield false if args.empty? && !block_given?

    case args.length
    when 1 then args.first.is_a?(Symbol) ? sym = args.first : result = args.first
    when 2 then result = args.first
                sym = args.last
    end


    result ||= 0
    my_each { |x| result = block_given? ? yield(result, x) : result.send(sym, x) }

    result
  end

我可以在此代码中添加什么以使其在字符串数组中搜索最长的单词并添加它?

标签: ruby

解决方案


string.split(" ")
      .max_by(&:length)

请参阅Enumerable#max_by


推荐阅读