Philip Cunningham music, code and stuff.

Ruby Euclidean Distance 13 December 2011

Short and sweet euclidean distance lambda in Ruby (1.9+).

#!/usr/bin/env ruby

euclidean_distance = ->(p1, p2) do
  Math.sqrt(p1.zip(p2).map {|coord| (coord[1]-coord[0])**2}.inject {|s,n| s+n})
end

EDIT: @mccraigmccraig made an even nicer version (see comments)!

#!/usr/bin/env rubyruby

euclidean_distance = ->(p1,p2) do
  p1.zip(p2).map{|a,b| a-b}.map{|d| d*d}.reduce{|s,d2| s+d2}.instance_eval{Math.sqrt(self)}
end

EDIT: Combine the ideas and we get something even nicer!

#!/usr/bin/env ruby

euclidean_distance = ->(p1, p2) do
  Math.sqrt(p1.zip(p2).map{|a,b| a-b}.map{|d| d*d}.reduce(:+))
end