开发者

how to call an item of an multidimensional array in ruby

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 f开发者_如何学Cind a solution.


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 ',' }


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜