Note that there are some explanatory texts on larger screens.

plurals
  1. POUnreproducible string comparison, forces elsif failure
    primarykey
    data
    text
    <p>In answering <a href="https://stackoverflow.com/questions/928563/code-golf-evaluating-mathematical-expressions">this code golf question</a>, I ran across a problem in my answer.</p> <p>I've been testing this and I cannot even get these two comparisons to work in the code, despite the fact that IRB has the right behavior. I <em>really</em> need some help here.</p> <p>Here's the code, below that will be an explanation of the problem.</p> <pre><code>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? &amp;&amp; chars[0] != ' ' &amp;&amp; n == '-') # only concatenate when it is part of a valid number s += n elsif (chars[0] == '(' &amp;&amp; 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 == ')' &amp;&amp; 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 &lt; 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 </code></pre> <p>The problem occurs in the assignment of <code>negate</code>.</p> <p>I need negate to be true when the character just before a expression is a dash, but the condition isn't even working. Both <code>n == '-'</code> and <code>n[0] == '-'</code>, the form of quotation doesn't matter, wind up FALSE every time. Yet, I've been using this exact comparison and <code>n == '('</code> works correctly every time!</p> <p>What is going on? Why doesn't <code>n == '-'</code> work, when <code>n == '('</code> does? This is encoded in UTF-8 w/o BOM, UNIX linebreaks.</p> <p>What's wrong with my code?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload