Dir.mkdir erases

G

gray

Hi, I'm just starting out with Ruby, but I noticed some behavior that
seemed counter-intuitive. I was hoping that someone could confirm this
behavior and help explain to me how I need to change my understanding
of the language.

The following code creates an array of filenames and stores them in
'directory'. When I attempt to create a new directory in the
filesystem using Dir, however, the 'directory' array is cleared. In
other words, these instructions print the directory contents only once:

directory = Dir.new(path)
Dir.chdir(path)

# prints the names of all files in path
directory.each { |x| print x + "\n" }

# make a new dir
Dir.mkdir 'foo'

# ?? where did the files go? This prints nothing...
directory.each { |x| print x + "\n" }

The way I understand it, the Dir.new() function creates an array of the
filenames in [path] and stores the reference in [directory]. Why does
the Dir object then clear this array when performing a simple mkdir?

Please keep in mind that my primary concern is understanding the
language, not just to get a piece of code that works.

I appreciate the help! ^^

-gray
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top