开发者

Looping through in ruby

开发者 https://www.devze.com 2023-04-12 13:08 出处:网络
Hi i have a database of users in a ruby project and i need to loop through each of them and get t开发者_如何学Cheir values. How do you loop? I know that you can use

Hi i have a database of users in a ruby project and i need to loop through each of them and get t开发者_如何学Cheir values. How do you loop? I know that you can use

model.find(i)

and get each element but how do you loop till the last element?


I assume you're using rails & active record. If so, do

User.all.each do |user|
  # your code here
end

or

User.find_each do |user|
  # your code here
end

The former loads all users from the database at once, the latter -- loads records in batches, which is helpful if you have a lot of records.

In ruby iterators are used a lot and usually the standard module called Enumerable is used for that: An Introduction to Ruby's Enumerable Module


As Ross said in his answer array.each is the best way to loop.

But in the case of ActiveRecord you should take a look at the Rails Guide section on Loading in Batches.

You could very easily say User.all.each, but if you have 1,000,000 users, this may well crash your server.

It's much better to say

User.find_each do |user|
  * do something *
end

And let Active Record look after your memory behind the scenes.


There are many ways to loops Say you have a users object

you can do

users.each do |user|

   puts user.name

end 

this is easiest way to loop

other ways could be using for loop, while loop other loops in rails http://www.tutorialspoint.com/ruby/ruby_loops.htm

0

精彩评论

暂无评论...
验证码 换一张
取 消