ruby-on-rails - 在 Ruby 中将值带入循环

标签 ruby-on-rails ruby

这几乎可以肯定是重复的,但我找不到原件 - 我不知道要使用的搜索词。这就是为什么我使用 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/

相关文章:

css - 如何在html中有选择地加载css?

css - 无法使用 Rails 迭代进行溢出

ruby-on-rails - Rails gem 编程 - 在推送到 gemcutter 之前如何尝试?

ruby - Ruby 的方法查找路径

ruby-on-rails - 来自 sidekiq 的 Action Cable Broadcast 消息仅在刷新后显示,从控制台立即生效

ruby-on-rails - 如何选择单一模型并坚持这种选择?

ruby-on-rails - Redcarpet 语法高亮

ruby - Devise + Omniauth 仅用于谷歌登录

ruby-on-rails - 权限被拒绝安装 rabl gem

ruby-on-rails - 从 iOS 应用程序连接到 ActionCable