# Getting the correct index in a ruby array in a javascript lo

**URL:** <https://www.ruby-forum.com/t/getting-the-correct-index-in-a-ruby-array-in-a-javascript-lo/197258>\
**Category:** Rails\
**Created:** [May 16, 2010, 3:16am UTC](https://www.ruby-forum.com/t/getting-the-correct-index-in-a-ruby-array-in-a-javascript-lo/197258 "2010-05-16T03:16:21Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![bfouts](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/5e9695/32.png) [@bfouts](https://www.ruby-forum.com/u/bfouts)\
**Post date:** [May 16, 2010, 3:16am UTC](https://www.ruby-forum.com/t/getting-the-correct-index-in-a-ruby-array-in-a-javascript-lo/197258/1 "2010-05-16T03:16:21Z")

</div>

So I’m very new to both ruby and javascript, but the basic problem is. I  
have a ruby array @events\_this\_month, and i’m running a javascript loop  
that basically needs the information from this array. The problem is I  
can’t seem to set the proper index for my ruby array. What I have looks  
like this:

for( var i = 0; i \< 3; i++)  
{  
var title = ‘\<%= @events\_this\_month[i].title %\>’;  
alert(title);  
}

I’ve also tried:

```
    <%= $j = 0 %>

```

for( var i = 0; i \< 3; i++)  
{  
var title = ‘\<%= @events\_this\_month[$j].title %\>’;  
alert(’\<%= $j %\>’);  
\<%= $j = $j +1 %\>  
}

Any suggestions on how I can access the correct index in my ruby array  
during the javascript loop?

---

<div class="post-metadata">

**Author:** ![bfouts](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/5e9695/32.png) [@bfouts](https://www.ruby-forum.com/u/bfouts)\
**Post date:** [May 16, 2010, 11:58am UTC](https://www.ruby-forum.com/t/getting-the-correct-index-in-a-ruby-array-in-a-javascript-lo/197258/2 "2010-05-16T11:58:17Z")

</div>

You’re confusing server side and client side code. Javascript works  
after a  
webpage has been returned but Ruby works when a page is being fetched.  
So if  
you want to be able to iterate over a bunch of values you’ll need to  
create  
a javascript array that contains the values of the Ruby array.

_If you want to convert it to a javascript array:_  
[http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html#M001761](http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html#M001761)

I suggest you just make an array of titles and then pass it in via an  
options array to your code or something to keep the view layer clean.

\*So in your controller set:  
\*options[:title]  
Equal to an array of the titles from your object array.

_Something like:_  
var myEvents = \<%= array\_or\_string\_for\_javascript(options[:title]) %\>;

for( var i = 0; i \< myEvents.length; i++)  
{  
alert (myEvents[i]);  
}

Someone correct me if I’m explaining anything wrong or if there is  
something  
wrong with my syntax – I’m beginning ruby and rails myself so I think  
that’s the correct syntax.

Tim
