This repository was archived by the owner on Oct 19, 2018. It is now read-only.
-
Couldn't load subscription status.
- Fork 18
Getting Rid of the BANG (!) notation
Mitch VanDuyn edited this page Jan 23, 2017
·
1 revision
currently we say
state.foo! 12
state.a_hash![:key] = 12
state.an_array! << 12Wouldn't it be nice if we could just say:
state.foo = 12
state.a_hash[:key] = 12
state.an_array << 12We would have to do something like this:
Add a method mutator to the Object base class.
mutator would take one of two forms:
class CountedSet
# CountedSet works like a set but if keeps track of how many times the item as been added to the set
def set
@set ||= Hash.new { |h, k| h[k] = 0 }
end
# use mutator to define methods that mutate the object's instance data
mutator :<< do |item|
set[item] += 1
end
def to_a
set.keys
end
... etc
end # for preexisting classes you can just give mutator a list of the method names that are mutators
Hash.mutator :[], :delete, ... etc ... list all the methods that mutate the underlying state.So the catch is we have to send mutator to all the base classes that have mutable operations. However once it's done it's done