Programming Questions

  • Newest
  • Popular Tags
  • Ask A Question
  • Longest Word Ruby
    I am stuck on this challenge. When I run the code it returns Nil. If anyone can help me understand what I am doing wrong, your assistance will be greatly appreciated. Thanks in advance.
    def LongestWord(sen)
    
      my_array = %w(sen)
      longest_word = ''
      my_array.each do |word|
      longest_word = word if longest_word.length < word.length
    
    end
    puts longest_word
    
    # code goes here
     
    end
    
    # keep this function call here 
    # to see how to enter arguments in Ruby scroll down   
    LongestWord(STDIN.gets)  
    
    rosskinney posted this question on 3/10/14 | ruby
    Answers
  • +
  • 4
  • -
  • When you use %w(sen), you are actually returning ["sen"] instead of the elements of the array. If you want to split the array by a space, just say
    my_array = sen.split
    
  • +
  • 1
  • -
  • You should also be able to do the `max_by` method which i think is bit more concise than .each, brings it down to a simpler one liner.
    longest_word = my_array.max_by { |x| x.length }
    
    Thanks for the regex part, im terrible at that stuff.
  • +
  • 1
  • -
  • Thanks so much for your help with this! I got the code to pass with this following line of code.
    my_array = sen.split(/[^\w-]+/)
  • +
  • 0
  • -
  •  my_array = sen.split(/[^\w-]+/)
    The bit in parentheses is a regular expression (regex): The first and last '/' simply designate the beginning and end of the regex [^\w-]+ essentually refers to any non-word characters A slightly more consice way to write it:
     my_array = sen.split(/\W+/)
    Check out rubular for breaking down regex's and seeing how they work: rubular.com/
  • +
  • 0
  • -
  • my_array = sen.split(/[^\w-]+/)
    Anyone explain to me what the bit inside the parentheses does?
  • +
  • 0
  • -
  • I have not seen the max_by method before. That is slick to be able to get that down to one sentence. There are so many different things to learn with Ruby. Thanks!
  • +
  • 0
  • -
  • You can also split the string between each character and pass the result to a new array: a = sen.split(//) # or a = sen.split("") I also wondered if you might want to use puts to return the answer. I often use puts to see what I'm doing and then comment it out (or not), and have my result return below it, for ex: def LongestWord(arg) answer = " " #most things happen here puts answer # comment this line out or not, won't affect that you've returned your answer return answer end
    Log in to write an answer.