Sieun Sim
Sieun Sim

Reputation: 71

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.

Upvotes: 0

Views: 72

Answers (2)

allknowingfrog
allknowingfrog

Reputation: 263

I believe send() will do what you need here, as Frederik Spang suggests. 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, i.e. try searching for "dynamically access Ruby methods".

Upvotes: 1

Frederik Spang
Frederik Spang

Reputation: 3454

You can use some light meta-programming with the send-method with an each-call:

<% [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. You can see the documentation on send method here: https://apidock.com/ruby/Object/send

Upvotes: 2

Related Questions