Ask Your Question

How to get an array index in erb template

asked 2014-01-09 04:56:49 -0600

jaksky gravatar image

updated 2014-01-09 04:59:03 -0600

Hi, I need to be able to generate following content of the file (for zookeeper installation):


when I have an array of server hostnames (example shows # of servers = 3). I tried something like following:

<% @regionserver_list.each do |this_server| -%>
server.  =<%= this_server %>:2888:3888
<% end -%>

That seems not correct as and I am struggling with getting an array index (need to start from 1). The point here is that the list of servers will be variable so I ... (more)

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2014-01-09 05:51:20 -0600

doc75 gravatar image

if I understood your issue well, you should use the following code (not checked on my side):

<% @regionserver_list.each_with_index do |this_server, idx| -%>
<%= "server.#{idx}=#{this_server}:2888:3888" %>
<% end -%>

Hope this helps (might need a to_s for idx, but not sure)

edit flag offensive delete link more


Hi, thanks for your quick post. It works there is a just one problem now. Array is indexed from 0 and I need to start from 1. Any trick how ...(more)

jaksky gravatar imagejaksky ( 2014-01-09 07:08:03 -0600 )edit

This one works as expected: <% @quorumserver_list.to_enum.with_index(1).each do |this_server, idx| -%> <%= "server.#{idx}=#{this_server}:2888:3888" %> <% end -%>

jaksky gravatar imagejaksky ( 2014-01-09 07:18:10 -0600 )edit

I am glad your issue is solved. You could also have used #{idx+1} inside the string I guess.

doc75 gravatar imagedoc75 ( 2014-01-09 10:15:32 -0600 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2014-01-09 04:56:49 -0600

Seen: 6,730 times

Last updated: Jan 09 '14