Created
July 14, 2020 11:31
-
-
Save caius/94fe60d726e580b88f2b3d20701f0bc3 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
@data = {} | |
def default_src(*args) | |
if args.first | |
@data[:default_src] = args.map(&:to_s) | |
else | |
@data.delete(:default_src) | |
end | |
end | |
# Initial state is blank | |
@data # => {} | |
# Setting a value for it, updates data as expected | |
default_src "none" # => ["none"] | |
@data # => {:default_src=>["none"]} | |
# Calling with no args wipes it out | |
default_src # => ["none"] | |
@data # => {} | |
# Given a value, trying to append in doesn't behave as expected | |
@data[:default_src] = ["none"] | |
default_src << "more" # => ["none", "more"] | |
@data # => {} | |
=begin | |
The really interesting bit is the default_src << "more" line. | |
This breaks down as | |
(default_src) ([result] << "more") | |
`default_src` follows the else branch inside the method, which removes the key/value from the @data hash | |
then returns that object that was just removed `["none"]` | |
We then execute `["none"] << "more"` which happily produces `["none", "more"]` **but that's not stored anywhere** | |
Then looking up the content of `@data` shows the source of truth knows nothing about our array shovelling. | |
=end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment