Search code examples
rubyarraysdictionaryenumerable

Array.map { |x| change value } is removing it from the array, why?


The objective is to move each letter to the next letter in the alphabet, within the map, it successfully changed the letter but once i'm out of there the value disappears, except the vowels. How come?

def LetterChanges(str)
  abc = [*("a".."z")]

  result = str.split(//)

  result.map! do |x| 

  if abc.include?(x)

    if x == "z"
       x = "A"
       else
       x = abc[abc.index(x)+1]

       # if you puts x here, you can see it changes value correctly

       if x == "a" || x == "e" || x == "i" || x == "o" || x == "u"
          x.capitalize!
          end
       end
    end

    #However here, the changed values that are not vowels disappear 
    # WHY is that happening, is the second if (vowel) affecting it? How?

end
puts "#{result.join}"  #<--- its only putting the vowels
return result.join  

end

LetterChanges("what the hell is going on?")  

Solution

  • The block passed to map! needs to return a value in all cases for this to work.

    http://www.ruby-doc.org/core-2.2.0/Array.html#method-i-map-21

    def LetterChanges(str)
      abc = [*("a".."z")]
    
      result = str.split(//)
    
      result.map! do |x| 
        if abc.include?(x)
          if x == "z"
             x = "A"
          else
             x = abc[abc.index(x)+1]
             if x == "a" || x == "e" || x == "i" || x == "o" || x == "u"
                x.capitalize!
              end
          end
        end
        x
      end
    
      result.join  
    end