Array.transpose

Didn’t know the Array.transpose method to create transposed matrix. Nice.

def calc(ary)
  ary.join(" + ") + " = " + ary.reduce(&:+).to_s
end

ary = [[4,9,2],[3,5,7],[8,1,6]]

puts "[row]"
puts ary.map {|a| calc(a) }
  # => 4 + 9 + 2 = 15
  # => 3 + 5 + 7 = 15
  # => 8 + 1 + 6 = 15

puts "[column]"
puts ary.transpose.map {|a| calc(a) }
  # => 4 + 3 + 8 = 15
  # => 9 + 5 + 1 = 15
  # => 2 + 7 + 6 = 15
Advertisements

Posted on February 14, 2013, in Ruby. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: