【问题标题】:Calling methods within methods to Titleize in Ruby在方法中调用方法以在 Ruby 中进行 Titleize
【发布时间】:2013-04-14 07:32:31
【问题描述】:

我正在尝试为编程作业创建一个标题化方法,它将某些单词大写而忽略其他单词。它总是将第一个单词大写。为此,我做了一个查找字符串第一个单词的方法,并尝试在 titleize 方法中调用它。我收到一条错误消息,上面写着“警告:条件中的字符串文字”。我试过改变 if 循环的措辞,但这并没有解决我的错误。谁能向我解释为什么我的代码被破坏了?非常感谢您的帮助!

def first_word(str)
    array = str.split(' ')
    return array[0]
end

def titleize(str)
    words = str.split
    words.each do |word| 
        if word != first_word(str)
            word.capitalize!
        elsif word != 'and' or 'the'
            word.capitalize!
        end
        words.join ' '
    end
end

【问题讨论】:

  • 顺便说一句:您的代码效率低下。考虑一个包含很多单词的非常长的字符串——拆分它会消耗时间和内存。在words.each 循环的每个循环中,您调用first_word(),它再次拆分整个字符串。最好使用first_word = words.first,并在循环中使用first_word 变量。
  • 您的代码错误地将与首字母相同的非首字母大写。
  • @sawa 你是对的!

标签: ruby capitalize


【解决方案1】:

更改以下内容

elsif word != 'and' or 'the'

elsif word != 'and' or word != 'the'

【讨论】:

    【解决方案2】:

    运算符!= 的优先级高于or。这意味着这一行

    elsif word != 'and' or 'the'
    

    等价于

    elsif (word != 'and') or 'the'
    

    而不是

    elsif word != ('and' or 'the')
    

    如您所料。后一个等价应表示为

    elsif word != 'and' or word != 'the'
    

    但即使在这种情况下,它也没有多大意义,而且很难阅读。

    您可能希望将链接更改为

    elsif !%w(and the).include?(word)
    

    【讨论】:

    • +1 表示“它没有多大意义,而且很难阅读”。该条件构造的可读性非常差。其中一部分是“'and' or”,这是合法的,但乍一看看起来就像一个语法错误。
    【解决方案3】:
    str = 'abc'
    p "hi" if str == '1' or '12'
    #=> warning: string literal in condition
    

    str = 'abc'
    p "hi" if (str == '1' or '12')
    #=> warning: string literal in condition
    p "hi" if '12'
    #=> warning: string literal in condition
    

    这发生在 ruby​​ 解释器看到您的代码如下:

    p "hi" if str == '1' or true
    

    第二个总是评估为真,因为'12' 总是存在的。警告是说,你有一个字符串文字 '12',而不是 booleantest,它总是计算为 true

    所以修复如下:

    p "hi" if str == '1' or str == '12' #=> "hi"
    p "hi" if ['1','12'].include? str #=> "hi"
    

    【讨论】:

      【解决方案4】:

      不确定它的可读性如何。但是很短!

      def titleize(str)
        str.capitalize.split.map do |word|
          %w{and the}.include?(word.downcase) ? word : word.capitalize
        end.join(' ')
      end
      

      【讨论】:

        猜你喜欢
        • 2012-07-08
        • 1970-01-01
        • 2019-03-28
        • 1970-01-01
        • 2011-08-11
        • 2013-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多