0
  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?

Randomize
  • 8,651
  • 18
  • 78
  • 133
Sanad
  • 15
  • 1
  • 3

3 Answers3

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

See Enumerable#max_by.

max
  • 96,212
  • 14
  • 104
  • 165
  • Just for fun, I'll point out that some natural languages don't separate words with spaces. Check out questions like https://stackoverflow.com/questions/3797746/how-to-do-a-python-split-on-languages-like-chinese-that-dont-use-whitespace if you're curious. :) – Jared Beck Aug 19 '20 at 22:26
1

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

Ben Simpson
  • 4,009
  • 1
  • 18
  • 10
  • I am sorry for this stupid question first not a string it's Array of strings and where to add it ? because it's not working – Sanad Aug 19 '20 at 18:57
  • Hi @Sanad, can you provide example. Whether you are trying to get the max string from an array of string like ` ['abc' , 'abcd', 'abcdef']` or its just a string like `'this is a string'` if its an array you can probably use `arr.max_by(&:length)` or if its a string you can probably use `str.split(' ').max_by(&:length)` – Syed Samiuzzaman Aug 20 '20 at 04:40
0

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)
nullTerminator
  • 396
  • 1
  • 6