在回答this code golf question時,我在答案中遇到了一個問題。不可重複的字符串比較,強制elsif失敗
我一直在測試這個,我甚至無法讓這兩個比較在代碼中工作,儘管IRB具有正確的行爲。我真的這裏需要一些幫助。
下面是代碼,下面將會解釋這個問題。
def solve_expression(expr)
chars = expr.split '' # characters of the expression
parts = [] # resulting parts
s,n = '','' # current characters
while(n = chars.shift)
if (s + n).match(/^(-?)[.\d]+$/) || (!chars[0].nil? && chars[0] != ' ' && n == '-') # only concatenate when it is part of a valid number
s += n
elsif (chars[0] == '(' && n[0] == '-') || n == '(' # begin a sub-expression
p n # to see what it breaks on, (or -
negate = n[0] == '-'
open = 1
subExpr = ''
while(n = chars.shift)
open += 1 if n == '('
open -= 1 if n == ')'
# if the number of open parenthesis equals 0, we've run to the end of the
# expression. Make a new expression with the new string, and add it to the
# stack.
subExpr += n unless n == ')' && open == 0
break if open == 0
end
parts.push(negate ? -solve_expression(subExpr) : solve_expression(subExpr))
s = ''
elsif n.match(/[+\-\/*]/)
parts.push(n) and s = ''
else
parts.push(s) if !s.empty?
s = ''
end
end
parts.push(s) unless s.empty? # expression exits 1 character too soon.
# now for some solutions!
i = 1
a = parts[0].to_f # left-most value is will become the result
while i < parts.count
b,c = parts[i..i+1]
c = c.to_f
case b
when '+': a = a + c
when '-': a = a - c
when '*': a = a * c
when '/': a = a/c
end
i += 2
end
a
end
問題發生在negate
的賦值中。
當表達式之前的字符是短劃線時,我需要否定,但條件不起作用。 n == '-'
和n[0] == '-'
,引用的形式都沒有關係,每次發送FALSE。然而,我一直在使用這個確切的比較,並且n == '('
每次都能正確工作!
這是怎麼回事?爲什麼n == '-'
不工作,當n == '('
呢?這是用UTF-8編碼,不帶BOM,UNIX linebreaks。
我的代碼有什麼問題?
非常感謝你,我沒有想到前面的聲明已經引起了我的代碼。謝謝你的新鮮眼睛。 – 2009-05-30 15:10:12