代码之家  ›  专栏  ›  技术社区  ›  Z Monk

Ruby 2.3.3中的手动标题化

  •  1
  • Z Monk  · 技术社区  · 8 年前

    def titleize(x)
      capitalized = x.split.each do |i|
        if i.length >= 2
          if i == "of" || "the" || "and"
            next
          else
            i.capitalize!
          end
        else
          next
        end
      end
      capitalized.join(' ')
    end
    

    以下是我的Rspec输出:

     1) Simon says titleize capitalizes a word
     Failure/Error: expect(titleize("jaws")).to eq("Jaws")
    
       expected: "Jaws"
            got: "jaws"
    
       (compared using ==)
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Sebastián Palma    8 年前

    你有一个 string literal in condition 警告:

    if i == "of" || "the" || "and"
    

    你在试着比较 i of the and

    if i == "of" || i == "the" || i == "and"
    

    更惯用的Ruby应该是使用 include?

    if ['of', 'the', 'and'].include?(i)
    

    这样至少你可以 Jaws

    war and peace 因为如果传递的字的长度小于或等于2,则它将执行 next peace .