【发布时间】:2013-10-30 15:30:17
【问题描述】:
所以我试图定义“#titleize”,一种将字符串中所有单词的首字母大写的方法,除了诸如“the”、“and”和“if”之类的绒毛词之外。 '
到目前为止我的代码:
def titleize(string)
words = []
stopwords = %w{the a by on for of are with just but and to the my had some in}
string.scan(/\w+/) do |word|
if !stopwords.include?(word)
words << word.capitalize
else
words << word
end
words.join(' ')
end
我的问题在于 if/else 部分 - 当我在字符串上运行该方法时,我收到“语法错误,意外 $end,期待关键字_end”。
如果我使用 if/else 的简写版本,我认为代码会起作用,它通常会进入 {花括号} 内的代码块中。我知道这个速记的语法看起来像
string.scan(/\w+/) { |word| !stopwords.include?(word) words << word.capitalize : words
<< word }
...与
words << word.capitalize
如果 !stopwords.include?(word) 返回 true 并且
words << word
在 !stopwords.include?(word) 返回 false 时发生。但这也不起作用!
它也可能看起来像这样(这是一种不同/更有效的方法 - 没有实例化单独的数组):
string.scan(/\w+/) do |word|
!stopwords.include?(word) word.capitalize : word
end.join(' ')
(来自Calling methods within methods to Titleize in Ruby) ...但是当我运行此代码时,我也会收到“语法错误”消息。
所以!有谁知道我所指的语法?你能帮我记住吗? 或者,您能否指出这段代码不起作用的另一个原因?
【问题讨论】:
标签: ruby if-statement boolean