简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM