Re: [Rails] rails 2D array access in Helper method
On Nov 1, 2013, at 9:20 AM, leo nike <lists@ruby-forum.com> wrote:
> Hi, I Want to simply print out 2d array elements. Method is located in
> Helper module. Calling helper method from jQuery. At the moment I'm not
> getting output (=> 0..3) I tried to do iterate through array via .each()
> method, but it would just print en entire array, however i want to
> access each element and convert it either to string or integer. can
> someone point me to possible solution? thanks!
>
> #app/helpers/controller_helper.rb
> def get_array
> database = SQLite3::Database.open("test.db")
> result = database.execute("select * from table1")
> print_array(result)
> end
>
> def print_array(array)
> for i in 0..array.length
> puts array[i][i]
> end
> end
>
> -------------------------------------------------------------------
> #app/views/controller/file.js.erb
> if($('.check_box1').is(':checked')){
> $("#div2").html("<%= get_array%>")
> }
>
> --
> Posted via http://www.ruby-forum.com/.
You don't want to use puts in there. You want to return the value so it gets evaluated in the erb code. puts returns nil, which means you get nothing inside the html element.
I'm not exactly sure from that method what you want inside div2 either.
Here's what I'd suggest:
def get_array()
# sqlite stuff as you have it
format_table(result)
end
def format_table(data)
out = "<table>\n"
out += data.map do |row|
format_row(row)
end.join("\n")
out += "\n</table>\n"
end
def format_row(row)
out = "<tr>"
out += row.map do |cell|
format_cell(cell)
end.join
out += "</tr>"
end
def format_cell(cell)
"<td>#{cell}</td>"
end
This will output html code, which seems like what you'd want at that point.
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/D5C254F6-6206-4D34-9BAB-E4CC1A39DE05%40gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home