ECM
ECM
总版主
总版主
  • 社区居民
  • 忠实会员
  • 原创写手
阅读:675回复:0

How to replace a pattern in a string

楼主#
更多 发布于:2016-05-30 21:31
I built a page that is rendered differently depending on params. The logic is something like this: <% if params[:x] == "1" %>
  <!--render version A-->
<% elsif params[:x] == "2" %>
  <!--render version B-->
<% elsif params[:x] == "3" %>
  <!--render version C-->
<% end %>
 I want each version to have two links which link to the other two versions, so the urls should have different params. I have a url string original_url, which is: "localhost:3000/page?x=1"
 and want to replace its parameter depending on params. The other two versions should be: "localhost:3000/page?x=2"
"localhost:3000/page?x=3"
 How can I eliminate the pattern ?x=[number] from original_url and replace it with something else? For version 1, I could do request.original_url.sub("?x=1", "?x=2")
 and then request.original_url.sub("?x=1", "?x=3")
 but then that wouldn't work on the other two versions.
answer(解决方案):

I would do this for the links <%= ([1,2,3]- [params[:x]]).each do |link_number| %>
   <%= link_to "Version #{link_number}", "/page?x=#{link_number}" %>
<% end %>
 This way everytime the page is loaded the link to the other 2 versions will exist. You could handle the partials through the controller (which seems better) or use something like: <%= render "version_#{['A','B','C'][params[:x] - 1]}" %>
 Without a better understanding of the problem I cannot assist beyond this point.

 

 

 

 

 

 

 

异常中心网是一家专门收集整理程序员编程过程中遇到的常见异常(exception)以及各种异常问答中心的网站。异常中心网旨在,减少程序员在编码遇到异常,处理各种异常时间和痛苦,让程序员能更愉快的、快速的定位异常并查找对应的异常解决方案。异常中心网诚心打造最完美的编程社区为程序员用户服务,努力成为最好的程序员乐园程序员社区程序异常中心程序bug中心异常问答中心

 

喜欢0 评分0
游客

返回顶部