Markus Fischer wrote:
> Can I, when I receive a string the first time from a source, "just add"
> some meta data to it, which I can later retrieve?

Sure. String and Array are both objects like any other Object.

(1) Instance variables

irb(main):001:0> s1 = "hello"
=> "hello"
irb(main):002:0> s1.instance_eval { @src = "terminal" }
=> "terminal"
irb(main):003:0> s1.instance_variables
=> ["@src"]
irb(main):004:0> s1.instance_variable_get(:@src)
=> "terminal"

Taking this further: you could make a subclass of String which has 
accessor methods.

(2) Singleton methods

irb(main):005:0> s2 = "world"
=> "world"
irb(main):006:0> def s2.source; "irb"; end
=> nil
irb(main):007:0> s2.source
=> "irb"

The only downside here is that an object with a singleton class cannot 
be serialized using Marshal.

(3) Delegation

This is the most flexible, and my preferred option. You have a wrapper 
object which contains your String, plus any other metadata object(s), 
and you forward requests to whichever object(s) makes sense for each 
action.

You can either do this using explicit forwarding, and/or method_missing, 
or libraries to handle this for you (look at delegate.rb in the standard 
library)

irb(main):001:0> require 'delegate'
=> true
irb(main):002:0> class MyStr < SimpleDelegator; attr_accessor :src; end
=> nil
irb(main):003:0> s3 = MyStr.new("hello")
=> "hello"
irb(main):004:0> s3.src = "irb"
=> "irb"
irb(main):005:0> s3
=> "hello"
irb(main):006:0> s3.src
=> "irb"

HTH,

Brian.
-- 
Posted via http://www.ruby-forum.com/.