Array question.

C

Catsquotl

Hi,
I have a csv file. #several really
That file is fed to the @points variable (see below) when creating an
instance of the class.
I'd like b[5] to hold an array of all remaining records in the file left
on that line.
Now it just pushes the 5th record. I can add b[6] which will get the
next record. But The number of records left vary....

I am building my app slowly. i'd like to be able to get the same
functionality somewhere in the middle also.
as i have 3 fixed variables in my Acupunt class and 2that can have more
than 1 value. I am guessing i have to look at a new approach here.
----------------------------------------------
def set_punten
@punten=[]
File.open("#{@points}", "r").each {|e|
e.chomp!
b=e.split(";")
@punten.push(Acupunt.new(b[0],b[1],b[2],b[3],b[4],b[5]))
}
end
 
7

7stud --

You can do something like this:

def test(*args) #gather all the args into an array
p args
end

arr = [10, 20, 30, 40, 50]

single_args = 3
args_for_def = []

single_args.times do
args_for_def << arr.shift
end
args_for_def << arr


test(*args_for_def) #split args_for_def into individual elements


--output:--
[10, 20, 30, [40, 50]]
 
R

Robert Klemme

Hi,
I have a csv file. #several really
That file is fed to the @points variable (see below) when creating an
instance of the class.
I'd like b[5] to hold an array of all remaining records in the file left
on that line.
Now it just pushes the 5th record. I can add b[6] which will get the
next record. But The number of records left vary....

I am building my app slowly. i'd like to be able to get the same
functionality somewhere in the middle also.
as i have 3 fixed variables in my Acupunt class and 2that can have more
than 1 value. I am guessing i have to look at a new approach here.

The string interpolation is pointless here. If @points may be anything
you can do @points.to_s which is still more efficient in case it is
actually a String.

Btw, you do not close the file handle properly! It's easier doing

File.foreach @points do |e|
....
end
e.chomp!
b=e.split(";")
@punten.push(Acupunt.new(b[0],b[1],b[2],b[3],b[4],b[5]))
@punten.push(Acupunt.new(b[0],b[1],b[2],b[3],b[4],b[5..-1]))

}
end

You could also use CSV class from standard library to get rid of the
need for parsing. See "ri CSV", e.g.

CSV.foreach(@points, :col_sep => ';') do |b|
...
end

Kind regards

robert
 

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

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top