假设我有
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"]
我希望b
根据a
的内容动态更新自己,以便最终b
打印出"a"
,因为"a"
是a
已从b
移除。我希望a
成为a
的单独对象;我不想修改map!
(无{{1}})。这可能吗?
答案 0 :(得分:1)
您似乎想要一个与另一个数组共享成员的依赖数组,但以不同方式显示数组成员。您可以使用Ruby closure执行此操作。
提供具有不同行为的单个数据集的多个表示的方法不止一种。但是,定义自定义类可能对您的用例而言过度。我认为将lambda分配给 b 是实现目标的最简单方法,至少在处理 a 和 b 作为单独但连接的对象。考虑:
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"]