This page has content which requires Javascript to be displayed correctly, such as LaTeX formulae or code snippets. Your browser doesn't seem to support Javascript. Sorry if this causes any problems.
Ruby Code Snippets
-
Watch a File for Changes
This script will watch a file for changes and execute a callback whenever the file is changed. It works by caching an
md5hash of the file and comparing it with the file periodically.require 'digest/md5' $md5 = '' def watch(file, timeout, &cb) $md5 = Digest::MD5.hexdigest(File.read(file)) loop do sleep timeout if ( temp = Digest::MD5.hexdigest(File.read(file)) ) != $md5 $md5 = temp cb.call(file) end end endUsage Example:
$num = 0 watch '../num_diff.rb', 1 do |file| puts "\e[31m MODIFIED: \e[0m \e[34m #{file} \e[0m (#{$num}, #{Time.now})" puts "\e[32m -- EXECUTING -- \e[0m" puts puts `ruby #{file}` puts puts "\e[32m -- FINISHED EXECUTION -- \e[0m" puts $num += 1 end
-
Octave's
diagGNU Octave has a
diagfunction which behaves like this:octave> diag([1,2,3]) ans = Diagonal Matrix 1 0 0 0 2 0 0 0 3To be more clear, diag \left( \begin{array}{ccc} 1 & 2 & 3 \end{array} \right) = \left( \begin{array}{ccc} 1 & 0 & 0 \\ 0 & 2 & 0 \\ 0 & 0 & 3 \end{array} \right)
This is an implementation of the
diagfunction in Ruby.# Create a diagonal matrix given a vector (or an array), # placing the entries of the vector on the diagonal of # the matrix. # For example, diag([1,2,3]) would give: # [ 1 0 0 ] # [ 0 2 0 ] # [ 0 0 3 ] # That would actually be a returned as a 2D array like this: # [[1, 0, 0], [0, 2, 0], [0, 0, 3]] # The array returned has to be converted to a matrix by doing # Matrix[ *diag(vector) ] def diag(vector) n = vector.size matrix = [] n.times do |i| matrix << Array.new(n) { |x| (x == i) ? vector[x] : 0 } end matrix end

This work by Vikhyat Korrapati is licensed under a Creative Commons Attribution 3.0 Unported License.