ruby here documents

情到浓时终转凉″ 提交于 2019-12-03 22:15:35

It looks like you're thinking of a heredoc as a sort of template, that you define once, with string interpolations built in, and then reuse. It isn't. As with any string definition, the string interpolation happens on the fly when the variable is defined.

So you would just do

def calcForm(left,op,right,result)
   <<HERE
     <input type="text" name="left" value=#{left}> 
     <select name="op">
     <option value="add" #{op}>+</option>
     <option value="mul" #{op}>*</option> 
     </select>
     <input type="text" name="right" value=#{right}> 
     =
     #{result}
   HERE
end

However, a better approach for what you're trying to do might be ERB, which works more like what you had in mind above; i.e. it is a template.

require 'erb'
template = ERB.new <<HERE
         <input type="text" name="left" value=<%=left%>> 
         <select name="op">
         <option value="add" <%=op%>>+</option>
         <option value="mul" <%=op%>>*</option> 
         </select>
         <input type="text" name="right" value=<%=right%>> 
         =
         <%=result%>
         HERE

def calcForm(left,op,right,result)
   template.result(binding)    
end

Note that binding here is a magic word that means "evaluate the expression in the current context"; i.e. with the currently defined variables (the parameters that were passed in).

The easiest answer is to define and return the string inside your method, and use the parameter names as the interpolation variables.

This should work:

def calcForm(left,op,right,result)
  <<HERE
<input type="text" name="left" value="#{left}"> 
<select name="op">
<option value="add" #{'selected' if op == 'add'}>+</option>
<option value="mul" #{'selected' if op == 'mul'}>*</option> 
</select>
<input type="text" name="right" value="#{right}"> 
=
#{result}
HERE
end

I added some quotes around your attributes to help with HTML validation. You don't need to explicitly write return or declare a local variable because the return value of the method will always be the value of the last ruby expression.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!