Christopher Ronning
Christopher Ronning

Reputation: 1890

How to generate variable names

I am iterating through this_dir,

this_dir = Dir.new(".")

putsing each .rb file. With the folders (everything that aren't .rb), I would like to open them, list their contents, and set them to a variable. I created an array names to get the variable name from, and planned to iterate through it by calling it with names_index and adding 1 to that.

names = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'm', 'o', 'p']
names_index = 0

Unfortunately, the closest thing I know how to do with Array values is puts them, which makes it a string.

this_dir.each do |file|
  if file.include?("*.rb")
    puts file
  else
    ....
  end
end

How do I turn the array values into variable names?

Upvotes: 0

Views: 94

Answers (2)

JVon
JVon

Reputation: 694

Jordan already showed you a better way to achieve whatever you're apparently trying to achieve. However, if for some reason you still want to do it the way you asked, I want to point out that this used to be possible back in Ruby 1.8. But for newer versions (as of time of writing this) you can't dynamically create local variables. But you can still achieve something similar using a hash:

names = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'm', 'o', 'p']
names_index = 0

table = {}

this_dir.each do |file|
  if file.include?("*.rb")
    puts file
  else
    table[names[names_index]] = file
    names_index += 1
  end
end

Now if a file different than .rb is found, it would be stored and you can access it like this:

table['a']

Which would return such file.

There is obviously little to no practical sense in doing this, and you should probably not do it anyway - but there it is for your curiosity.

Upvotes: 1

Jordan Running
Jordan Running

Reputation: 106017

If you just want to list all of the .rb files in a directory and its subdirectories, use Dir.glob with the ** pattern to recurse subdirectories, like so:

Dir.glob('./**/*.rb').each do |file|
  puts file
end

In general it doesn't make sense to dynamically create variable names for the purpose of storing many items. In such cases (when a better solution like Dir.glob above isn't available) you should just use an Array (or sometimes a Hash).

Upvotes: 2

Related Questions