3 Replies - 557 Views - Last Post: 05 October 2018 - 04:50 PM Rate Topic: -----

#1 Lemur   User is offline

  • Pragmatism over Dogma
  • member icon


Reputation: 1453
  • View blog
  • Posts: 3,633
  • Joined: 28-November 09

Destructuring in Ruby

Posted 04 October 2018 - 10:12 PM

Turns out it's possible to do destructuring on method arguments in Ruby! It's a bit of a trip, but you can do this after:

destructure def adds(a: 1, b: 2)
  a + b
end

adds(a: 1, b: 2)
# => 3

adds(OpenStruct.new(a: 1, b: 2))
# => 3

Foo = Struct.new(:a, :b )
adds(Foo.new(1,2))
# => 3



This article explains how exactly it works, and it's a trip!

https://medium.com/@...by-9e9bd2be0360

Is This A Good Question/Topic? 1
  • +

Replies To: Destructuring in Ruby

#2 modi123_1   User is online

  • Suitor #2
  • member icon



Reputation: 15362
  • View blog
  • Posts: 61,611
  • Joined: 12-June 08

Re: Destructuring in Ruby

Posted 05 October 2018 - 05:48 AM

I am not following.. Assuming 'destructuring' is in the classic sense - is that functionality provided by ruby, or did you have to make your own function?

Is it a trip for being a long journey or just crazy?
Was This Post Helpful? 0
  • +
  • -

#3 NeoTifa   User is offline

  • NeoTifa Codebreaker, the Scourge of Devtester
  • member icon





Reputation: 4604
  • View blog
  • Posts: 19,323
  • Joined: 24-September 08

Re: Destructuring in Ruby

Posted 05 October 2018 - 08:42 AM

I've no idea what's going on and I've been using ruby for years.
Was This Post Helpful? 0
  • +
  • -

#4 Lemur   User is offline

  • Pragmatism over Dogma
  • member icon


Reputation: 1453
  • View blog
  • Posts: 3,633
  • Joined: 28-November 09

Re: Destructuring in Ruby

Posted 05 October 2018 - 04:50 PM

It's redefining the original method to take either an object or its original keywords. If an object is given it attempts to extract the values from that object by the name of the arguments.

If we have a Point with properties for x and y, and a function like so:

destructure def go_north(x:, y:)
  Point.new(x, y + 1)
end



and we called it with an actual point:

Point = Struct.new(:x, :y)

go_north(Point.new(0, 0))
=> Point(0, 1)



It could take either a Hash or a literal point object and still get the relevant values for X and Y.

Consider Javascript argument destructuring:

function goNorth({ x, y }) {
  return { x, y: y + 1 }
}



Same general idea.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1