开发者

How to get row and column length of a 2-dimensional array in rails 3?

can somebody tell how to get the row and column length of a 2-dimensional array in rails 3?

My array goes like this:


 payroll = Array.new[Payroll.count][2]

When we are getting the length of a 1-dimensional array we do like

 array.length 
How about in a 2-dimensional array?

Im thinking of doing something like开发者_StackOverflow中文版:


 payroll = Array.new[Payroll.count][2]

 for i in 0..payroll.row.length - 1
  for j in 0..1
   puts payroll[i][j]
  end
 end

I just wanna know the right way. Pls help...


A two dimensional array is just an array of arrays, so just use payroll.length to get the height and payroll[0].length to get the width (assuming all rows are the same width). Here's what your loop looks like using that idea:

for i in 0..payroll.length - 1
  for j in 0..payroll[i].length - 1
    puts payroll[i][j]
  end
end

But an easier way to loop through an array is using an iterator method. Here I'll change the for loops to each.with_index (use each_with_index if your Ruby doesn't support each.with_index):

payroll.each.with_index do |row, i|
  row.each.with_index do |cell, j|
    puts payroll[i][j]
  end
end

And now I'll make it even simpler since I'm assuming you don't really need access to the indexes at all, just the individual elements in the array:

payroll.each do |row|
  row.each do |cell|
    puts cell
  end
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜