Sanad
Sanad

Reputation: 15

How to search for the longest word in the string

  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

What can I add to this code to make it search for the longest word in Array of strings and were add it?

Upvotes: 0

Views: 107

Answers (3)

nullTerminator
nullTerminator

Reputation: 396

Some assumptions:

  1. Each array item only contains one word
  2. You only want the longest word returned, not the position
words = %w[tiny humungous antidisestablishmentarianism medium]

puts words.max_by(&:length)

Upvotes: 0

max
max

Reputation: 101976

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

See Enumerable#max_by.

Upvotes: 3

Ben Simpson
Ben Simpson

Reputation: 4049

What can I add to this code to make it search for the longest word in a string

"this is a test of the emergency broadcast system".split(' ').sort {|x,y| y.length <=> x.length}.first

To break this down we:

  • assign a sentence as a string
  • split that string into words
  • sort each word by comparing its length with the previous word's length
  • take the first result

More information on sorting in Ruby at https://apidock.com/ruby/v2_5_5/Enumerable/sort

Upvotes: 1

Related Questions