0

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.

1
  • I'm sorry, not a string but a path. Commented Dec 3, 2017 at 15:06

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you a lot. I cannot understand 100% what "send" do exactly, but the problem is solved!
What Send does, basically, is to call a method. It simply calls the method that has the name of the first argument
1

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".

1 Comment

You're right. It's always difficult for me to search programmatic problems in English. From now on, I will try to translate the name of concept first as your advise. Thanks a lot!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.