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.
How about that:
def f((a, b), (c, d))
[a, b, c, d]
end
f([1, 2], [3, 4]) # ==> [1, 2, 3, 4]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With