如何替换字符串中的模式 [英] How to replace a pattern in a string

查看:55
本文介绍了如何替换字符串中的模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我构建了一个页面,该页面根据 params 的呈现方式有所不同。逻辑是这样的:

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

我希望每个版本都有两个链接,链接到其他两个版本,因此网址应具有不同的参数。我有一个URL字符串 original_url ,它是:

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"

如何消除模式?x = [number] from original_url 并替换为其他内容?

How can I eliminate the pattern ?x=[number] from original_url and replace it with something else?

对于版本1,我可以这样做

For version 1, I could do

request.original_url.sub("?x=1", "?x=2")

然后

request.original_url.sub("?x=1", "?x=3")

但是在其他两个版本上将无法使用。

but then that wouldn't work on the other two versions.

推荐答案

我会针对链接执行此操作

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

这样,每次加载页面时,都会存在指向其他2个版本的链接。

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.

这篇关于如何替换字符串中的模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆