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

tfyh

joss

Josselin wrote:

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

On 7/8/06, Josselin [email protected] wrote:

for user in @users
if (user.has_role? (‘manager’))

end
end

tfyh

joss

You could use
for user in @users.collect{ |u| u if u.has_role?(“manager”) }
stuff
end

but effectively your iterating over you user collection more than once.
Once through for the initial collect, then once through whatever was
found.

There is no conditional statement that I know of to short circuit a loop
through except to include a conditional inside the loop.

Hi,

In message “Re: IF test in FOR loop”
on Sun, 9 Jul 2006 01:05:23 +0900, Josselin [email protected]
writes:

|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.

On 7/8/06, Yukihiro M. [email protected] wrote:

|for user in @users (user.has_role? (‘manager’))

for user in @users
next if user.has_role? (‘manager’)

I like this one specifically, but try “unless” please :wink:

                                                    matz.


Deux choses sont infinies : l’univers et la bêtise humaine ; en ce qui
concerne l’univers, je n’en ai pas acquis la certitude absolue.

  • Albert Einstein

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs