Array.map { |x| change value } 正在从数组中删除它,为什么?
Array.map { |x| change value } is removing it from the array, why?
objective是将每个字母移动到字母表中的下一个字母,
在地图中,它成功地改变了字母,但是一旦我离开那里,除了元音之外,值就消失了。怎么来的?
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?")
传递给 map!
的块在所有情况下都需要 return 一个值才能正常工作。
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
问题是你的if。当 x 不是元音时 return 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
objective是将每个字母移动到字母表中的下一个字母, 在地图中,它成功地改变了字母,但是一旦我离开那里,除了元音之外,值就消失了。怎么来的?
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?")
传递给 map!
的块在所有情况下都需要 return 一个值才能正常工作。
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
问题是你的if。当 x 不是元音时 return 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