Harry
Harry

Reputation: 165

Update one array based on another array

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

Answers (1)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

TL;DR

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.

Create a Closure with a "Stabby" Lambda

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

Related Questions