Completely dumb iterator question from a newbie

Hi all,

So I have a question about iteration. Here’s some code I saw on Ruby on
Windows:

inbox.Items.each do |message|
message.Attachments.each do |attachment|
filename = “c:\attachments\#{attachment.FileName}”
attachment.SaveAsFile(filename)
File.delete(filename) if File.size(filename) < 500000
end
end

What I find troubling is ‘message,’. How do we know the variable to
iterate over? I have the same issue with VBScript, where the same code
would be:

For each objMessage in colItems

            Etc.

Next

The thing that’s bothering me is where people decide the thing to
iterate over. How do you decide what to put between the pipes | |?

Sorry for the retarded question,

Ron

Ron,

Don’t worry, no question is ‘retarded’ or dumb. You can decide to put
any sane string between the pipes. However, for the sake of readability
and helpfulness to other programmers who read your code, using an
obvious short form or the entire word is preferred (for me; your mileage
may vary).

  • Michael B.

Steckly, Ron wrote:

inbox.Items.each do |message|
message.Attachments.each do |attachment|
filename = “c:\attachments\#{attachment.FileName}”
attachment.SaveAsFile(filename)
File.delete(filename) if File.size(filename) < 500000
end
end

The thing that’s bothering me is where people decide the thing to
iterate over. How do you decide what to put between the pipes | |?

There’s no magic about the word “message”. It’s just a variable name.
You get to pick it. The magic is that the each method goes through each
(aha! that’s why it’s called “each”) element in inbox.Items and assigns
the element to the variable you named between the pipes.

Of course, once you pick a name to use you have to use it consistently.
If you used “msg” between the pipes, you have to use “msg” instead of
“message” throughout the code between do and end.

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