gpt4 book ai didi

ruby - 如果/否则作为{代码块}?

转载 作者:太空宇宙 更新时间:2023-11-03 17:53:25 25 4
gpt4 key购买 nike

所以我正在尝试定义“#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,期待 keyword_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 )...但我在运行此代码时也收到“语法错误”消息。

所以!有谁知道我指的语法?你能帮我记住吗?或者,您能否指出这段代码不起作用的另一个原因?

最佳答案

我认为你错过了一个end:

string.scan(/\w+/) do |word|
if !stopwords.include?(word)
words << word.capitalize
else
words << word
end
end #<<<<add this

对于速记版本,请执行以下操作:

string.scan(/\w+/).map{|w| stopwords.include?(w) ? w : w.capitalize}.join(' ')

关于ruby - 如果/否则作为{代码块}?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19506394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com