Topic: What to Do?

Hi, I'm only a newbie on ruby could someone help me with my code:
Here's: I'm writing a program which will ask the user to input a word or typed goodbye to quit the program. The first part is done the problems is that how can i find the longest word?
example:
Type a word (or goodbye to quit): Hello
Type a word (or goodbye to quit): Hello Hello
Type a word (or goodbye to quit): goodbye

The longest word is “Hello Hello”

can someone help me with my simple program?

Code:
loop do
puts

Re: What to Do?

I assume you are storing the user input in an array?

If so, you would have an array like ...

user_input = ["hello", "hello Hello", "goodbye"]

I can quickly think of 2 ways to handle this.

1) As each input is entered, check the length of the input and if it is larger than the current value, store it.

index = max_length = 0

loop to get input
  inputs << input
  if input.length > max_length
    max_length = input.length
    index = inputs.size - 1
  end  
end

puts "The longest word is \"#{inputs[index]}\""

2) After the keyword is entered to quit the program, loop through all the elements of the array and check the size of each entry and then return end result.

index = max_length = 0

loop to get input
  inputs << input
end

inputs.each_with_index do |x, i|
  if x.length > max_length
    max_length = x.length
    index = i
  end
end

puts "The longest word is \"#{inputs[index]}\""

Option #1 should have the best performance since it saves you from having to loop through the array of user input.

Re: What to Do?

You don't need to loop through, you can just order the strings by length. 

longest = user_input.sort_by(&:length).last

jmesserer - do you know how ruby loops work?  You seem to be building large unecessarily complicated loops.  Why do you need index in there?  Don't muck about with indexes unless you need to.   Even if i was to do it your way with a loop i would just do

longest = ""
user_input.each do |input|
  if input.length > longest.length
    longest = input
  end
end

###########################################
#If i've helped you then please recommend me at Working With Rails:
#http://www.workingwithrails.com/person/ … i-williams

Re: What to Do?

Max - Of course I know how loops work. I was just using pseudo code for the main loop that gets the users input since winshock3r said he already had that part working.

I did not think about just storing the actual longest value as each input is processed, that is a great solution. The reason I was storing the index of the longest value was to reference it in the array so looping through it was not required.

Thinking about performance on a large dataset (and it probably would have to be massive), sorting the entire array by value length could be costly so it would be best to just check the length (and store it if it is the new 'longest' value) after the user inputs it. This comment is taking this discussion too far ;-).