Reputation: 15
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
Reputation: 396
Some assumptions:
words = %w[tiny humungous antidisestablishmentarianism medium]
puts words.max_by(&:length)
Upvotes: 0
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:
More information on sorting in Ruby at https://apidock.com/ruby/v2_5_5/Enumerable/sort
Upvotes: 1