-
-
Save roktas/88b114f871a34c4ab72d121d86fb9e8a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# frozen_string_literal: true | |
require 'delegate' | |
class Deck < DelegateClass(::Hash) | |
attr_reader :choosen | |
def initialize(choosen = nil, **initial) | |
super(initial) | |
@choosen = | |
if choosen | |
raise ArgumentError, "Invalid key: #{choosen}" unless initial.key? choosen | |
choosen | |
else | |
keys.first | |
end | |
end | |
def shuffle | |
lookup = keys.zip(new_keys = keys.shuffle).to_h.invert | |
self.class.new(lookup[@choosen], **keys.zip(values_at(*new_keys)).to_h) | |
end | |
def shuffle! | |
@choosen = (new_deck = shuffle).choosen | |
replace new_deck | |
self | |
end | |
def choosen_value | |
self[choosen] | |
end | |
def self.[](...) | |
new(...) | |
end | |
end | |
d = Deck[A: 1, B: 2, C: 3, D: 4, E: 5] | |
pp d | |
pp d.values | |
pp d.choosen | |
pp d.choosen_value | |
d.shuffle! | |
pp d | |
pp d.values | |
pp d.choosen | |
pp d.choosen_value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment