Skip to content

Instantly share code, notes, and snippets.

@MollsReis
Created February 6, 2012 23:04
Show Gist options
  • Save MollsReis/1755729 to your computer and use it in GitHub Desktop.
Save MollsReis/1755729 to your computer and use it in GitHub Desktop.
Retrieve diagonals from array of arrays in Ruby
class Array
def diagonals
[self, self.map(&:reverse)].inject([]) do |all_diags, matrix|
((-matrix.count + 1)..matrix.first.count).each do |offet_index|
diagonal = []
(matrix.count).times do |row_index|
col_index = offet_index + row_index
diagonal << matrix[row_index][col_index] if col_index >= 0
end
all_diags << diagonal.compact if diagonal.compact.count > 1
end
all_diags
end
end
end
@nimamehanian
Copy link

Hi Scott. I'm studying your diagonals method, and I'm trying to follow what is going on, but I'm not understanding the flow. I'd really appreciate it if you could walk me through what is happening. I played with it in Pry. The output makes sense too. I just want to know, step-by-step, what you're doing. Thank you.

Nima

@MollsReis
Copy link
Author

Hey I must have missed this comment when you made it a few months ago. I know its a bit late, but did you ever get to understanding the flow?

@YevKo
Copy link

YevKo commented Dec 4, 2014

yeap, it is really hard to understand. comments in the code would help

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment