Elegant Ruby

Ruby lends itself to some syntactically elegant solutions, like in this program that swaps diagonally opposed elements in a matrix.

def swapDiagonals(matrix)
  matrix.each_with_index.map do | row, row_index |
    row.each_with_index.map do | element, col_index |
      if col_index == row_index
        row[row.length - row_index - 1]
      elsif  col_index == row.length - row_index - 1
        row[row_index]
      else
        element
      end
    end
  end
end

input:
 [[1,2,3], 
 [4,5,6], 
 [7,8,9]]

output:
[[3,2,1], 
 [4,5,6], 
 [9,8,7]]
[Read More]

Functional and Recursive Ruby

This program returns Squares. From a functional perspective, the use of a variable for the ‘range_object’ is technically a side-effect, but I include it here for sake of clarity.

Range objects are a good example of the kind syntactic sugar that I sometimes felt was lacking in JavaScript.

class Squares
  def initialize(n)
    @number = n
  end

  def square_of_sum
    def factorial(n)
      n == 1 ? 1 : n + factorial(n - 1)
    end

    factorial(@number) ** 2
  end

  def sum_of_squares
    range_object = 1..@number
    range_object.reduce { | a, b | a + b ** 2 }
  end

  def difference
    square_of_sum - sum_of_squares
  end
end