我正在尝试从juliabox读取终端输入。问题是,它接受输入的唯一方法是我把答案放在引号之间。在我的情况下,我必须使用“是”或“否”来获得正确的行为。
response = readline()
if response == "yes"
有什么方法可以将输入转换为字符串以消除对引号的需要?
答案 0 :(得分:3)
最明确的做法是"是"在你的例子中。 " "字符创建字符串类型。
> typeof("yes")
ASCIIString
或者,您可以存储字符串并与之进行比较:
yes_str = "yes"
no_str = "no"
if response == yes_str
# yes stuff
end
或一个干净的想法,检查多个回复:
yes_strs = ["yes", "y", "yeah", "sure", "ok", "ya", "positive", "affirmative", "pos"]
no_strs = ["no", "n", "nah", "nope", "na", "negative", "negatory", "neg"]
# Convert to lower case for matching
response = lowercase(readline())
if response in yes_strs
# yes stuff
elseif response in no_strs
# no stuff
else
println("I don't understand, give me a yes or no.")
# other stuff
end