Created
December 7, 2023 17:30
-
-
Save molawson/436c5e86da8fc1b4de41575a48726a40 to your computer and use it in GitHub Desktop.
Destructuring Ruby objects with pattern matching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Thing | |
attr_reader :name, :type | |
def initialize(name, type) | |
@name = name | |
@type = type | |
end | |
def deconstruct_keys(_keys) | |
{ name:, type: } | |
end | |
end | |
thing = Thing.new("foo", "bar") | |
thing => { name:, type: } | |
name # => "foo" | |
type # => "bar |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More pattern matching details: https://docs.ruby-lang.org/en/master/syntax/pattern_matching_rdoc.html