【问题标题】:Index is nil in each loop (Ruby)每个循环中的索引为零(Ruby)
【发布时间】:2020-04-06 19:10:57
【问题描述】:

所以我正在尝试制作一个名为 titleize 的小函数。它接受一个字符串,用空格将其拆分为一个数组,如果它是一个限定词(第一个词或任何不是以下之一的词:the, and over),则在用空格连接数组之前将其大写.

我查看了几个 Ruby 样式指南,它们警告不要使用 for/while 循环来支持内置的语言时间和每个循环。由于我的问题的领域需要索引,并且数组在 Ruby 中都是可迭代和可索引的,因此我尝试使用带有两个参数 item 和 index 的 each 循环。我的问题是我的索引为零(我已经对此进行了测试)。我的语法错误还是我遗漏了什么?我在网上环顾四周,找不到与此相关的任何内容以及类似的问题。这是我的第一个问题,如果我在发这篇文章时遗漏了任何规则,我想提前道歉。

它应该做什么: “桂河大桥”->“桂河大桥” 它能做什么: “桂河大桥”->“桂河大桥”

def titleize(string)
  words = string.split
  capitalized_words = []
  words.each do |word, index|
    #adds words if they are the first word or not one of the following: and, the, over
    if(!(word == "and" || word == "the" || word == "over") || index == 0)
      capitalized_words.push(word.capitalize)
    else
      capitalized_words.push(word)
    end
  end
  capitalized_words.join(" ")
end

【问题讨论】:

标签: ruby


【解决方案1】:

each 不给你索引。试试each_with_index

words.each_with_index do |word, index|

无论如何,我会这样做

TO_NOT_CAPITALIZE =  %w(and the over)

def titleize(string)
  string.split.each_with_index.map do |word, index| 
    index.zero? || !TO_NOT_CAPITALIZE.include?(word) ? word.capitalize : word 
  end.join(' ')
end

【讨论】:

  • 那行得通。感谢您让我了解迭代器的不同实现 :)
  • 我的荣幸先生
猜你喜欢
  • 2019-04-06
  • 2011-02-20
  • 2020-07-19
  • 2016-11-08
  • 2012-10-19
  • 2011-06-16
  • 1970-01-01
  • 2013-06-03
  • 1970-01-01
相关资源
最近更新 更多