-
-
Save roktas/f526d08120c74767ca3e43a063797728 to your computer and use it in GitHub Desktop.
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
# 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], **new_keys.zip(values_at(*new_keys)).to_h) | |
end | |
def shuffle! | |
@choosen = (new_deck = shuffle).choosen | |
replace new_deck | |
self | |
end | |
def self.call(...) | |
new(...) | |
end | |
end | |
d = Deck.(A: 1, B: 2, C: 3, D: 4, E: 5) | |
pp d | |
pp d.values | |
d.shuffle! | |
pp d | |
pp d.values | |
pp d.choosen |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment