kortes
kortes

Reputation: 33

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?")  

Upvotes: 0

Views: 87

Answers (2)

Daniel Zambrano
Daniel Zambrano

Reputation: 46

The problem is your if. When x is a not a vowel that return nil.

Just Change this line

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

With this

x = %w{a e i o u}.include?(x) ? x.capitalize : x

Upvotes: 1

danielrsmith
danielrsmith

Reputation: 4060

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

Upvotes: 1

Related Questions