Prime Number - Data while loading
I was trying in Ruby on Rails how to find a prime number. Here is my code :
helper : app/helpers/test_helper.rb
module TestHelper
def prime_number? number
index = 2
tmp = 0
while index <= number
if tmp < 1
if (number % index) == 0
tmp += 1
end
else
return false
开发者_StackOverflow社区end
index += 1
end
return true
end
end
and my view : app/views/test/index.html.erb
<% (2..100).each do |i| -%>
<% if prime_number? i %>
<%= i %>
<% end -%>
<% end -%>
So my question is : How can you load data while it's calculating ? I mean if I replace 100 by 100000 in my view, how can I see data on my view while my helper method is calculating ? Do I need to use ajax or rails provide a tool for that ?
Thank you.
Short answer: yes, you'll need AJAX.
Longer answer: you can use the Prototype Helper periodically_call_remote to poll one of your actions and add new prime numbers to the end of the list.
There is an issue though, Ruby is very slow compared to native OS languages such as C. If you want to get the most prime number results, I'd write the prime number code in C and find a mechanism to access the results. One way to do that would be to have your C application write prime numbers to a file and you can tail -f that file to get the new primes. I'm sure you can find a C example for finding prime numbers somewhere.
Even if you were to write the prime number code in Ruby, you'd have to run it as a separate process from your Rails application for it to continually calculate primes, so you might as well do it in something faster. Actually, Ruby might not be too terribly slow for this calculation, it'd be interesting to benchmark the two.
精彩评论