Reputation: 165
Let's say I have
a = ["a","b","c","d","e","f","g"]
b = a.map(&:upcase)
a.delete("a")
print b # right now b = ["A","B","C","D","E","F","G"]
# I want b = ["B","C","D","E","F","G"]
I want b
to dynamically update itself based on what a
has so that, in the end, b
prints out without "a"
because "a"
was removed from a
. I want b
to be a separate object from a
; I do not want to modify a
in place (no map!
). Is this possible?
Upvotes: 0
Views: 95
Reputation: 84343
You appear to want a dependent array that shares members with another array, but displays the array members differently. You can do this with a Ruby closure.
There's more than one way to provide multiple representations of a single data set with varying behavior. However, defining a custom class might be overkill for your use case. I think assigning a lambda to b is the easiest way to accomplish what you want, at least in the sense of treating a and b as separate-but-connected objects. Consider:
a = %w[a b c d e f g]
b = ->{ a.map(&:upcase) }
a.delete ?a
b.call
#=> ["B", "C", "D", "E", "F", "G"]
a
#=> ["b", "c", "d", "e", "f", "g"]
Upvotes: 1