Ruby getting the diagonal elements in a 2d Array

Posted by Calm Storm on Stack Overflow See other posts from Stack Overflow or by Calm Storm
Published on 2010-03-24T09:49:49Z Indexed on 2010/03/24 9:53 UTC
Read the original article Hit count: 162

Filed under:
|

Hi, I was trying some problems with my 2D ruby array and my LOC reduces a lot when I do array slicing. So for example,

require "test/unit"

class LibraryTest < Test::Unit::TestCase

  def test_box
    array = [[1,2,3,4],[3,4,5,6], [5,6,7,8], [2,3,4,5]]
    puts array[1][2..3] # 5, 6
    puts array[1..2][1] # 5, 6, 7, 8
  end
end

I want to know if there is a way to get a diagonal slice? Lets say I want to start at [0,0] and want a diagonal slice of 3. Then I would get elements from [0,0], [1,1], [2,2] and I will get an array like [1,4,7] for example above. Is there any magic one-liner ruby code that can achieve this? 3.times do {some magic stuff?}

© Stack Overflow or respective owner

Related posts about ruby

Related posts about beginner