ERB模板中的代数数字符号操作

问题描述

我有一个ERB模板:

<%
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%>$
...

问题在于,当b为负数时,我得到了两倍的负值。示例:

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

有没有办法避免这种情况,而是将+代替--

解决方法

使用if语句:

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

如果b == 0,您可能还想考虑做一些不同的事情(但是我不知道!)?

,

这将起作用:(代替-b,您也可以说b.abs

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

或者,通过字符串操作:

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...