0

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?

2
  • Just using a.map(&:upcase) shouldn't modify in place. Commented Oct 5, 2014 at 0:48
  • @Undo The OP wants a dependent array that shares members, but displays the array members differently. Same contents, but different behavior. It's likely an X/Y problem, but it's certainly doable with minimal ceremony using Proc or lambda. Commented Oct 5, 2014 at 3:50

1 Answer 1

1

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"]
Sign up to request clarification or add additional context in comments.

1 Comment

This is very interesting and suits my purposes quite well. Thank you very much. I have to say, the Proc class is very cool.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.