Skip to content

Instantly share code, notes, and snippets.

@yrps
Last active December 4, 2015 22:54
Show Gist options
  • Select an option

  • Save yrps/111ad4fb65ec8f669130 to your computer and use it in GitHub Desktop.

Select an option

Save yrps/111ad4fb65ec8f669130 to your computer and use it in GitHub Desktop.
extend Ruby's standard Matrix module to facilitate Rational matrices
require 'matrix'
class Matrix
# Attempt to recast each entry of the matrix to clazz
def to(clazz)
self.each_with_index do |entry, i, j|
self[i, j] = send(clazz.name.to_sym, entry)
end
end
end
@yrps

yrps commented Dec 4, 2015

Copy link
Copy Markdown
Author
irb(main):001:0> load 'matrix-convert.rb'
=> true
irb(main):002:0> a = Matrix[ [1, 2], [-3, 4.5] ]
=> Matrix[[1, 2], [-3, 4.5]]
irb(main):003:0> a.to Rational
=> Matrix[[(1/1), (2/1)], [(-3/1), (9/2)]]

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