2013-04-21 49 views
0

我想为编程任务创建一个标题化方法,它将大写某些单词并忽略其他单词。它总是首字母大写。为此,我创建了一个方法来查找字符串的第一个单词,并试图在titleize方法中调用它。我得到一个错误,说“警告:条件字符串文字”。我试着改变周围的if循环的语句,但它并没有解决我的错误。任何人都可以解释为什么我的代码被破坏?非常感谢你的帮助!在Ruby中标题化的方法中调用方法

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 
+2

顺便说一句:你的代码是低效的。考虑一个很长的字符串与许多单词分裂它消耗时间和内存。在'words.each'循环的每个循环中,您都会调用'first_word()',它再次分割整个字符串。最好先做'first_word = words.first',然后在循环中使用'first_word'变量。 – tessi 2013-04-21 09:06:48

+1

您的代码错误地将与初始单词相同的非初始单词大写。 – sawa 2013-04-21 09:39:55

+0

@sawa你是对的! – 2013-04-21 09:45:17

回答

1

更改以下

elsif word != 'and' or 'the' 

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

操作!=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) 
+0

+1,因为“它不会很有意义,而且很难阅读”。该条件构造的可读性非常差。其中一部分是“'”和“or'”,这是合法的,但它*看起来像乍一看语法错误。 – 2013-04-21 10:52:11

1
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 

第二总是会评估为t rue,因为'12'总是存在。警告是说,而不是booleantest,您有一个字符串文字,'12',其始终计算为true

所以一个解决方法是如下:

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

不知道如何读这个。但它很短!

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