IF test in FOR loop

J

Josselin

is it possible to test a condition (true-false) for each element in a
loop like this :

for user in @users (user.has_role? ('manager'))
.....
end

or shoudl I write an if condition inside the loop :

for user in @users
if (user.has_role? ('manager'))
....
end
end

tfyh

joss
 
D

Daniel Schierbeck

Josselin said:
is it possible to test a condition (true-false) for each element in a
loop like this :

for user in @users (user.has_role? ('manager'))
....
end

or shoudl I write an if condition inside the loop :

for user in @users
if (user.has_role? ('manager'))
....
end
end

For starters, I would use #each instead of the `for' magic. Second, if
you only wish to process a sub-group of the items, select those first,
and then iterate over them:

@users.select{|user| user.has_role? 'manager'}.each do |user|
# ...
end

It may not be faster, but I think it's easier to read and understand.
You could also split it up, if you prefer:

managers = @users.select{|user| user.has_role? 'manager'}
managers.each{|manager| ...}


Cheers,
Daniel
 
Y

Yukihiro Matsumoto

Hi,

In message "Re: IF test in FOR loop"

|is it possible to test a condition (true-false) for each element in a
|loop like this :
|
|for user in @users (user.has_role? ('manager'))
|....
|end
|
|or shoudl I write an if condition inside the loop :
|
|for user in @users
| if (user.has_role? ('manager'))
| ....
| end
|end

for user in @users
next if user.has_role? ('manager')
....
end

or

@users.select{|user| x.has_role?('manager')}.each do |user|
...
end

or anything you like.

matz.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,208
Messages
2,571,082
Members
47,683
Latest member
AustinFairchild

Latest Threads

Top