Cli*_*amp 5 ruby destructuring
你能直接在 Ruby 中解构函数参数吗:
def get_distance(p1,p2)
x1,y1 = p1
x2,y2 = p2
((y2-y1)**2 + (x2-x1)**2)**0.5
end
Run Code Online (Sandbox Code Playgroud)
我尝试了显而易见的:
def get_distance([x1,y1],[x2,y2])
((y2-y1)**2 + (x2-x1)**2)**0.5
end
Run Code Online (Sandbox Code Playgroud)
但是编译器不喜欢那样。
那个怎么样:
def f((a, b), (c, d))
[a, b, c, d]
end
f([1, 2], [3, 4]) # ==> [1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)