Cliff Stamp
Cliff Stamp

Reputation: 571

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.

Upvotes: 9

Views: 5893

Answers (2)

Parker Tailor
Parker Tailor

Reputation: 1485

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

Upvotes: 1

Nondv
Nondv

Reputation: 819

How about that:

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

f([1, 2], [3, 4]) # ==> [1, 2, 3, 4]

Upvotes: 18

Related Questions