Ruby—在if语句中添加多个include
我有下面的代码,它工作得很好Ruby—在if语句中添加多个include,ruby,if-statement,include,Ruby,If Statement,Include,我有下面的代码,它工作得很好 if user_input.include? "s" user_input.gsub!(/s/ "th") else print "Nothing to change" end 但是当我想添加另一个include时,它无法识别elsif如何将这些include添加到一起 if user_input.include? "s" user_input.gsub!(/s/ "th") elsif user_input.include? "cee"
if user_input.include? "s"
user_input.gsub!(/s/ "th")
else
print "Nothing to change"
end
但是当我想添加另一个include
时,它无法识别elsif
如何将这些include添加到一起
if user_input.include? "s"
user_input.gsub!(/s/ "th")
elsif user_input.include? "cee"
user_input.gsub!(/cee/ "th")
else
print "Nothing to change"
end
您的代码显示错误:
SyntaxError: unexpected ')', expecting keyword_end
你忘了gsub中的逗号
if user_input.include? "s"
user_input.gsub!(/s/, "th")
elsif user_input.include? "cee"
user_input.gsub!(/cee/, "th")
else
print "Nothing to change"
end
编辑:
如果要进行两次更换,则需要更改为:
old_value = user_input
if user_input.include? "s"
user_input.gsub!(/s/, "th")
end
if user_input.include? "cee"
user_input.gsub!(/cee/, "th")
end
if user_input == old8value
print "Nothing to change"
end
这是因为if-else语句的执行流。 如果“If”中的条件匹配,则不会执行“elseif”块
if user_input.include?('s') or user_input.include?('cee')
user_input.gsub!(/s/,"th").gsub!(/cee/,"th")
else
print "Nothing to change"
end
因为
gsub
返回nil
如果没有更改,您可以这样编写示例:
unless user_input.gsub!(/s|cee/ "th")
print "Nothing to change"
end
一旦匹配了第一个
(如果
),则跳过其余的
对于您的特定用例,我建议您使用单个gsub
,如下所示:
regexp = /s|cee/
if string.match(regexp)
string.gsub!(regexp, "th")
else
"Nothing to gsub!"
end
你能添加一个输入/输出的例子吗?谢谢你整理了错误,但是它仍然忽略了“s”的包含,它只替换了“cee”,你想同时替换吗?你不能喜欢这个。Else是指“在另一种情况下”。如果第一条语句完成了,其他语句就没有了。谢谢,这很有意义,因为每个查询都需要两条独立的If语句。谢谢您的解决方案和解释:)