1

This is a very specific question (which I doubt most will be able to benefit from) but I'll explain:

I have an example file which contains numbers split by commas on each line:

1,2,3,4
5,6,7,8
abcdefg
1.3.4

I want to be able to split the file into lines (easily done):

file = File.open(filename)
file = file.read.split("\n")

And now I want to split each line into an array if it includes "," and have the name or the array be something like: 1array (with 1 being the file line index)

Something like this would be preferable:

file.each_with_index |c, i| do # c=content, i=index
  if c.include? ","
    instance_array_set("@#{i}array", c.split(","))
  end
end

I've looked everywhere for anything on an instance array concept but I can't seem to find anything. I am open to completely different ways of doing what I'm trying to do (as long as it's not too long).

Thanks in advance (hopefully)

0

3 Answers 3

1

Variables' identifiers can't start with a digit so I move it to the end of the name

File.open(filename).read.split("\n").each_with_index do |item, index|
  if item.include?(",")
    instance_variable_set("@array#{index}", item.split(","))
  end
end
Sign up to request clarification or add additional context in comments.

8 Comments

So instance variables don't need to be single variables? They can be arrays as well?
of course. they are just names. you can assign anything to a variable
Now I think about it, that makes a whole lot of sense. Thanks. Also, how would I go about calling one of the instance variables that I don't know the name of? For example: array1 = 1 array2 = 2 array3 = 3 i=1 Could I call array1 like this?: array#{i} = 1+1
Well, you're right. In fact, I don't know why you prefer set instance variables rather then have a result array with every array who pass the test in it. So that you can iterate it, take a random array from it or do whatever you want to
Consider using IO::foreach to avoid the creation of a temporary array: File.foreach(fname).with_index { |line,i| instance_variable_set("@array#{index}", line.chomp.split(",")) }.
|
0

Build an array of arrays:

result =
  File.readlines('/tmp/input').map do |line|
    values = line.chomp.split(',')
    values if values.size >= 2
  end.compact

result[0][2]
#⇒ "3"

Comments

0

Yet another version:

File.readlines(filename).select{ |e| e.split("").include? "," }.map{ |e| e.chomp.split "," }

# => [["1", "2", "3", "4"], ["5", "6", "7", "8"], ["11", "12", "13"]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.