這似乎是一個奇怪的問題。我已經得到了一些帶有輸入字符串的Ruby代碼,它使用scan
和flatten
來提取特定的值,然後希望在if...then
聲明中使用該值,但我遇到了問題。評估Ruby正則表達式和變量
我的輸入字符串描述了區域中'危險的生物'的數量。當描述沒有危險的生物或兩個或更多的生物時,字符串總是標準的,例如:
「區域內沒有危險的生物」或「一個危險的生物......」等等。
我用這個來取代代表生物數量的詞:「no」,「one」,「two」等,希望稍後將它們轉換爲數值 - 「no」= 0 「一個」= 1,等
要做到這一點,我用:
crittercount = strcheck.scan(/a*(no|one|two|three|four|five|six|seven|eight|nine|ten)a*/)
然後我就變crittercount
去,做一個if then
說:
if crittercount == "no"
critters = 0
... exit and go do something with the var...
end
我做這對每一個即(當我得到這個問題想通了,我會用if..elsif..end
)
if crittercount == "one"
critters = 1
... exit and go do something with the var...
end
...
crittercount == "ten"
後,我只是用
if crittercount == "ten"
critters = 10
else
critters = 99
end
這裏有一個問題:我有一個名爲maxcreatures
等於10
變量。例如,我拿「該地區沒有危險的生物」的strcheck
值作爲例子,我打印出它返回的確切字符串的值。然後我打印出crittercount變量,在這個例子中,我得到了「no」。
當我通過我的if..then..
聲明得到不過,我評價一下用做:
if critters > maxcreatures
print "Maximum Creatures " + critters.to_s + " and maximum is #{maxcreatures}. Lets Bail"
else
print "Critter count " + critters.to_s + " is less than #{maxcritters} Keep going."
end
在任何情況下我越來越99
,我發誓我用盡了一切。我嘗試在正則表達式的末尾使用.flatten
,我試着在crittercount
var上使用.strip
。我希望有人看着這個,去'呃,試試這個。'
根據要求這裏是所有的代碼,有來電在這裏等功能,可能沒有什麼意義......
maxcritters = 2
critters = 0
put "count critter"
strcheck = matchfind "You notice ?"
crittercount = strcheck.scan(/a*(no|one|two|three|four|five|six|seven|eight|nine|ten)a*/)
echo strcheck
echo crittercount
crittercount = crittercount.strip
if crittercount == "no"
critters = 0
goto "roundup"
end
if crittercount == "one"
critters = 1
goto "roundup"
end
if crittercount == "two"
critters = 2
goto "roundup"
end
if crittercount == "three"
critters = 3
goto "roundup"
end
if crittercount == "four"
critters = 4
goto "roundup"
end
if crittercount == "five"
critters = 5
goto "roundup"
end
if crittercount == "six"
critters = 6
goto "roundup"
end
if crittercount == "seven"
critters = 7
else
critters = 99
end
roundup:
if critters > maxcritters
echo "Maximum Creatures " + critters.to_s + " and maximum is #{maxcritters}. Lets Bail"
critters == nil
fput "retreat"
else
echo "Critter count " + critters.to_s + " is below maximum of #{maxcritters} - We're cool. Keep going."
critters == nil
goto "combatcheck"
end
請出示您遇到問題的確切代碼。 –
我一直希望避免這種情況,因爲在它的範圍之外有對Ruby函數的調用,但我會將其添加到主要問題中。 – user401093
你在正則表達式中有什麼'a *'?這似乎是你的問題的原因之一。 – sawa