【发布时间】:2013-12-28 10:10:49
【问题描述】:
我正在尝试在 Ruby 中编写一个非常简单的方法,该方法接受一个字符串和一个单词数组,并检查字符串是否包含任何单词,如果包含,则将它们替换为大写。
我尝试了,但由于我的 Ruby 技能水平,它不是很好。
def(my_words,my_sentence)
#split the sentence up into an array of words
my_sentence_words = my_sentence.split(/\W+/)
#nested loop that checks the words array for each brand
my_sentence_words.each do |i|
my_words.each do |i|
#if it finds a brand in the words and sets them to be uppercase
if my_words[i] == my_sentence_words[i]
my_sentence_words[i] == my_sentence_words[i].up.case
end
end
end
#put the words array into one string
words.each do |i|
new_sentence = ("" + my_sentence_words[i]) + " "
end
end
我得到:can't convert string into integer error
【问题讨论】:
-
一件事你使用
i两次,内部循环使用j。其次,您没有给函数命名。列出完整的错误。 -
提供有意义的示例数据
-
“有关您编写的代码问题的问题必须在问题本身中描述具体问题 - 并包含重现问题的有效代码。有关指导,请参阅 SSCCE.org。”
-
当您获得使用 Ruby 的经验时,您会发现循环索引的频率几乎不像您习惯使用
C等那样频繁。您将更多地依赖each和Enumerable“mixin”(模块)中的众多方法,几乎所有这些方法都是用each实现的。