7

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.

Cliff Stamp
  • 531
  • 5
  • 11
  • 1
    In #1, if `p1` and `p2` are each 2-element arrays, that should work fine. In #2 try `get_distance(((x1,y1), (x2,y2))`, assuming you are calling the method `get_distance(a,b)`, where `a` and `b` are each 2-element arrays. I don't understand, however, why you are asking this question, as it is covered in every book on Ruby, and in countless blogs and articles. I just googled, "Ruby destructuring", which produced many hits. The first was [this one](http://tony.pitluga.com/2011/08/08/destructuring-with-ruby.html). – Cary Swoveland Aug 10 '18 at 17:13
  • 3
    On another note, `**0.5` is nearly twice as slow as simply using `Math.sqrt`, you aren't doing yourself any favors there, and it doesn't read as well. – ForeverZer0 Aug 10 '18 at 17:35

2 Answers2

15

How about that:

def f((a, b), (c, d))
  [a, b, c, d]
end

f([1, 2], [3, 4]) # ==> [1, 2, 3, 4]
Nondv
  • 769
  • 6
  • 11
1

As well as destructuring array parameters, you can also destructure hashes. This approach is called keyword arguments

# Note the trailing colon for each parameter. Default args can be listed as keys
def width(content:, padding:, margin: 0, **rest)
  content + padding + margin
end

# Can use args in any order
width({ padding: 5, content: 10, margin: 5 }) # ==> 20
Parker Tailor
  • 1,290
  • 13
  • 12
  • 3
    This isn't really destructuring. If your hash has an extra parameter, the method call will fail. For "true" has destructuring one should add an additional parameter: `def f(a:, **rest)` which will capture the rest keys – Nondv Dec 03 '20 at 19:51
  • Thanks for the clarification! I'll update my answer – Parker Tailor Feb 01 '22 at 05:41