[英]Ruby on rails- How can I insert a variable into a string in array?
I want to make a repetition using: for. 我想使用:重复。
For example, 例如,
<li class="<%= is_active?([y17s_index_path,y17s_gun_path]) %>"><a href='<%= y17s_index_path%>'>2017</a></li>
<li class="<%= is_active?([y16s_index_path,y16s_gun_path]) %>"><a href='<%= y16s_index_path%>'>2016</a></li>
<li class="<%= is_active?([y15s_index_path,y15s_gun_path]) %>"><a href='<%= y15s_index_path%>'>2015</a></li>
<li class="<%= is_active?([y14s_index_path,y14s_gun_path]) %>"><a href='<%= y14s_index_path%>'>2014</a></li>
.
.
.
How can I write repetitive statement in this case? 在这种情况下,我该如何写重复性声明? I tried #{} but It does not work.
我尝试#{},但它不起作用。
I want to change only 17,16,15... these numbers. 我只想更改17,16,15 ...这些数字。
You can use some light meta-programming with the send
-method with an each-call: 您可以在每次调用的
send
方法中使用一些简单的元编程:
<% [1..17].each do |i| %>
<li class="<%= is_active?([send("y#{i}s_index_path"), send("y#{i}s_gun_path")]) %>"><a href='<%= send("y#{i}s_index_path") %>'>20<%= "%02d" % i %></a></li>
<% end %>
Should output 2001 to 2017, with same methods as before. 应使用与以前相同的方法输出2001年至2017年。 You can see the documentation on
send
method here: https://apidock.com/ruby/Object/send 您可以在此处查看有关
send
方法的文档: https : //apidock.com/ruby/Object/send
I believe send()
will do what you need here, as Frederik Spang suggests. 我相信
send()
会按照Frederik Spang的建议做您需要的事情。 I would just add that "dynamic access" is the common term for what you're describing. 我只想补充一下,“动态访问”是您所描述的通用术语。 Having a name for the concept will help a lot if you want to search for more information, ie try searching for "dynamically access Ruby methods".
如果您想搜索更多信息,即尝试搜索“动态访问Ruby方法”,则为该概念起个名字会很有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.