Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 491
Cliff Stamp Avatar asked Aug 10 '18 17:08

Cliff Stamp


2 Answers

How about that:

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

f([1, 2], [3, 4]) # ==> [1, 2, 3, 4]
like image 142
Nondv Avatar answered Nov 14 '22 08:11

Nondv


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
like image 42
Parker Tailor Avatar answered Nov 14 '22 07:11

Parker Tailor