【发布时间】:2015-04-07 20:05:03
【问题描述】:
目标是将每个字母移动到字母表中的下一个字母, 在地图中,它成功地改变了字母,但是一旦我离开那里,这个值就会消失,除了元音。怎么会?
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?")
【问题讨论】:
-
当字符 (
x) 不在abc中时,您的块值是多少?如果x是'w'怎么样?手动或在调试器中逐步执行代码。或者将其转换为 lambda (f = lambda do |x| if abc.include?(x) ... end),以便您可以使用各种输入轻松评估irb中的块。 -
感谢 mu - 如果它不在 abc 中,我想要相同的值,所以我认为如果它不满足任何 if 条件,它只会保留 (x) 值。怎么没有发生?是什么让 (x) 失去了创建时的价值?
标签: ruby arrays dictionary enumerable