这几乎可以肯定是重复的,但我找不到原件 - 我不知道要使用的搜索词。这就是为什么我使用 Stackoverflow 而不是 Google :)
无论如何,这是我的代码:
def titleize(say)
index = 0
words = say.split
words.each do |word|
unless word == "and" || "or" || "over" || "the" || "for"
word.capitalize!
end
if index == 0
word.capitalize!
end
index += 1
end
say = words.join(" ")
end
因为索引是在循环之前声明的,所以我的 if index == 0
不起作用。
我如何让 Ruby 知道并使用我的对象索引?另外:这叫什么?
最佳答案
使用 index == 0
非常好,因为在循环中可以访问索引。您真正的问题可能出在这一行:
word == "and" || "or" || "over" || "the" || "for"
这总是 true
-like!你的意思是:
["and", "or", "over", "the", "for"].include? word
除此之外还有一个名为 each_with_index
的方法,您可以像这样使用它:
words.each_with_index do |word, index|
关于ruby-on-rails - 在 Ruby 中将值带入循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25068195/