在回答这个代码高尔夫问题时,我在回答中遇到了一个问题。
我一直在对此进行测试,尽管 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 换行符。
我的代码有什么问题?