目标是将每个字母移动到字母表中的下一个字母, 在地图中,它成功地改变了字母但是一旦我离开那里,除了元音之外,价值消失了。怎么会?
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?")
答案 0 :(得分:1)
传递给map!
的块需要在所有情况下都返回一个值才能生效。
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
答案 1 :(得分:1)
问题是你的问题。当 x 不是返回nil的元音时。
只需更改此行
if x == "a" || x == "e" || x == "i" || x == "o" || x == "u"
x.capitalize!
end
有了这个
x = %w{a e i o u}.include?(x) ? x.capitalize : x