Algebraic number signs manipulation in ERB templates

Viewed 47

I have an ERB template:

<%
a = rand(-10..10)
b = rand(-10..10)
c = rand(-10..10)

%>

The solution of this equation $<%=a%>x + <%=b%> = <%=c%>$ is 

$<%=a%>x = <%=c%> - <%=b%>$
...

The problem is that when b is negative I get double minus. Example:

$2x = 4--2$
# a = 2, b= -2, c= 3, I get 

Is there a way to avoid that and put + instead of --

2 Answers

Use an if statement:

<%= b > 0 ? '-' : '+' %>

You might also want to consider doing something different (but I don't know what!) if b == 0?

This would work: (instead of -b you could also say b.abs)

<% if b.negative? -%>
  $<%= a %>x = <%= c %> - <%= -b %>$
<% else -%>
  $<%= a %>x = <%= c %> + <%= b %>$
<% end -%>

Or, via string manipulation:

$<%= a %>x = <%= "#{c} + #{b}".sub('+ -', '- ') %>$
Related