我正在编写一个程序来为一种语言生成单词。这是我的代码:
def correct(list)
unless @vowel
filter_consonants(list)
similarity_avoidance(list)
end
puts "Corrected list: " + list
return list
end
def similarity_avoidance(list)
puts list.size
sublist = ""
subsublist = ""
list.each_char do |character|
sublist += character if similarity_exists?(character, @root)
end
sublist.each_char do |character|
subsublist += character if @root.include?(character)
end
sublist.each_char do |character|
sublist.delete!(character) if subsublist.include?(character)
end
sublist += subsublist
list.each_char do |character|
list.delete!(character) if sublist.include?(character)
end
list += sublist
puts "Corrected for similarity: " + list
end
当函数更改了一串字符时,字符串中的某些字符就会消失。我不知道我做错了什么或不管我是谁。有谁知道什么?
答案 0 :(得分:1)
您没有将传递给函数的字符串对象的值更改为参数list
。你正在做的是在函数体内为list
分配一个不同的字符串对象。 list
不是对象,它是对一个或另一个对象的引用 - 函数参数列表中的list
与外部list
不同的引用功能。重命名参数,澄清问题会很有帮助。
您需要做的是将内部价值提供给外部。在函数中执行此操作的机制是return语句。
尝试从函数返回(inside)list
的新值,并在调用函数时将函数返回值分配给外部list
。
同样的逻辑适用于您尝试更改list
值的两个函数。您还需要在list
结束时返回filter_consonants
。
def correct(list)
unless @vowel
list = filter_consonants(list)
list = similarity_avoidance(list)
end
puts "Corrected list: " + list
return list
end
def similarity_avoidance(list)
puts list.size
sublist = ""
subsublist = ""
list.each_char do |character|
sublist += character if similarity_exists?(character, @root)
end
sublist.each_char do |character|
subsublist += character if @root.include?(character)
end
sublist.each_char do |character|
sublist.delete!(character) if subsublist.include?(character)
end
sublist += subsublist
list.each_char do |character|
list.delete!(character) if sublist.include?(character)
end
list += sublist
puts "Corrected for similarity: " + list
return list
end