From: Walton Hoops Date: 2010-05-16T11:44:46+09:00 Subject: Re: Accessing elements of a ruby array with javascript On 5/15/2010 6:45 PM, Brandon Jake12jake wrote: > 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? > First off, since you didn't specify anything I'll assume your using Rails. What I'd suggest is first turning your Ruby array into a java-script array. Rails adds an easy method to do this: to_json. If your not using rails you can get the same method with the 'json' or 'json_pure' gems. This is what I came up with in a quick and dirty test: Note: this is a Ruby list, not a Rails list. The more appropriate place for Rails would be the list at: http://groups.google.com/group/rubyonrails-talk