Search code examples
rubydestructuring

Ruby destructuring in function parameters


Can you destructure function parameters directly in Ruby :

def get_distance(p1,p2)
  x1,y1 = p1
  x2,y2 = p2
  ((y2-y1)**2 + (x2-x1)**2)**0.5
end

I tried the obvious :

def get_distance([x1,y1],[x2,y2])
  ((y2-y1)**2 + (x2-x1)**2)**0.5
end

But the compiler didn't like that.


Solution

  • How about that:

    def f((a, b), (c, d))
      [a, b, c, d]
    end
    
    f([1, 2], [3, 4]) # ==> [1, 2, 3, 4]