1

I have an array like this

i = 0 lines.each do |l| array[i] = l.split(',') i+=1 end 

and I want call $array[1][3] like in php, but it didnt worked. I've google it over hours now, and can't find a solution.

2
  • 3
    When you say "didn't work" you didn't actually tell us when wrong. Did you get the wrong answer, did you see an error message, did your computer explode into a shower of purple elephants? Commented Apr 13, 2011 at 15:18
  • 1
    sry i had a windows related error, i started my ubuntu and it worked my way Commented Apr 13, 2011 at 15:37

2 Answers 2

2

First of all a few enhancements to your codez:

# initialize your vars array = [] lines.each do |l| array << l.split ',' # use the << operator end 

Now in ruby the dollar symbol for arrays is not necessary, it denotes global variables and it's not good practice to use them.

You should access your variable like this: array[1][3].

You can make your code a one liner in ruby1.9:

array = lines.each_line.map {|l| l.split ',' } 
Sign up to request clarification or add additional context in comments.

2 Comments

what's wrong with the ruby 1.8 way? array = lines.collect{|l| l.split ','}
@Simon nothing particularly, I added that just as a bonus refactor. It's presuming that lines is a string could be also rewritten for 1.8.7 like array = lines.split("\n").map{|l| l.split ',' }.
0

If your problem is that calling array[6][3] returns something like Error: method [] undefined for nil, then do this instead:

array[6].to_a[3] 

Whenever either the row (6) or the column (3) is out of range, it gives back nil. to_a ensures that, even when the row is out of range, it still gives an empty array so that search for column does not return an error.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.