I have trouble understanding the use of <end> statement

hello everyone,
Please consider the following code. I got it to work but by trial and error. I don’t really understand why the commands are where they are. I only understand the last - that shows the where the code ends. Can somebody explain the other s please.
Thank you.


# Write a method that takes in a string. Return the longest word in
# the string. You may assume that the string contains only letters and
# spaces.
#
# You may use the String `split` method to aid you in your quest.
#
 

def longest_word(sentence)
  v=sentence.split(" ")
  lw=nil 
  i=0 
  while i<v.length
  crW=v[i]
  if lw==nil 
    lw=crW 
    elsif crW.length>lw.length 
    lw=crW
  end #THIS IS THE PART WHERE I DON'T GET
    i+=1 
  end 
  return lw 
 
end

# These are tests to check that your code is working. After writing
# your solution, they should all print true.

puts("\nTests for #longest_word")
puts("===============================================")
    puts(
      'longest_word("short longest") == "longest": ' +
      (longest_word('short longest') == 'longest').to_s
    )
    puts(
      'longest_word("one") == "one": ' +
      (longest_word('one') == 'one').to_s
    )
    puts(
      'longest_word("abc def abcde") == "abcde": ' +
      (longest_word('abc def abcde') == 'abcde').to_s
    )
puts("===============================================")

def longest_word(sentence)
  # split the string by the space character creating an array of strings.. or our list of words.
  v=sentence.split(" ")

  # assign a variable to use to store the longest word
  lw=nil 
  # assign a variable to use as a counter to run through list of words
  i=0 

  # start a while loop using the counter
  while i<v.length
    # assign a variable containing the current word
  crW=v[i]
    # if this is the first loop the lw variable is nil, so just assign it.
  if lw==nil 
    lw=crW 

  # if the the current words length is greater than the lw variables length, assign lw to the current word
  elsif crW.length>lw.length 
    lw=crW
  end # the end is here is say there are no more conditions to the if

    # increment the counter by adding 1 to it
    i+=1 

  end # this end is here to define the end of the while loop
 
  # here we return what we determined to be the longest word
  return lw 
 
end
3 Likes

If you are new to Ruby I highly recommend getting a book - we are so lucky to have some amazing books :023:

Have a look at my recommendations here: Best way to learn Ruby & Rails – (via @AstonJ) (some of them are free - good luck!)

2 Likes