Object reference handle (like perl's reference to scalar)

#Below is what I think is a general purpose solution to making
#references. I provide several ways to do it. Here is an
#example:

···

Eric Mahurin [mailto:eric_mahurin@yahoo.com] wrote:

#
#a = (0..5).to_a -> [0,1,2,3,4,5]
#w = ref{"a[2..4]"} # uses eval
#x = a.ref[2..4] # uses [] and []= methods
#y = a.ref("[]","[]=",2..4) # specify methods manually
#z = a.ref(["[]",2..4],["[]=",2..4]) # unique args to get/set
#w[] -> [2,3,4]
#x[] -> [2,3,4]
#y[] -> [2,3,4]
#z[] -> [2,3,4]
#w[]=(11..14).to_a
#a -> [0,1,11,12,13,14,5]
#x[]=[4,3,2]
#a -> [0,1,4,3,2,14,5]
#y[]=[0,1]
#a -> [0,1,0,1,14,5]
#z[]=[2,3,4]
#a -> [0,1,2,3,4,5]

cool.

is it possible to remove the [] appendix? :slight_smile:

something like,

hacker = ["bot","pen","a",5,10]

name = hacker.ref[0..2]
fname = name.ref[0]
lname = name.ref[1]
mname = name.ref[2]

height = hacker.ref[3..4]
feet = height.ref[1]
inches = height.ref[2]

fname = "Eric"
lname = "Mahurin"
mname = "?"

feet = 6
inches = 5

name #=> ["Eric","Mahurin","?"]
height #=> [6,5]
hacker #=> ["Eric","Mahurin","?",6,5]

Possible?

btw, i cannot download your reference gem...

thanks and kind regards -botp

This is not possible, unfortunately.
In Ruby,
    fname = "Eric"
is just an assignment to a local variable. There are no method calls
involved, and nothing to intercept.

You can, of course, go even further and remove the =, leaving:
    fname "Eric"
Reminds me of Traits (nee Attributes).
In this case, "fname" would be a method, which means it would not be an
object. You could create a thing like this using code like the
following:

def define_attribute(method_name)
  singleton_class = (class << self; self end)
  singleton_class.instance_eval do
    define_method method_name do |*args|
        if args.empty?
          instance_variable_get("@#{method_name}")
        else
instance_variable_set("@#{method_name}", *args)
        end
    end
  end
  singleton_class
end

define_attribute :fname #=> #<Class:#<Object:0x...>>
fname "Eric" #=> "Eric"
fname #=> "Eric"

# or even on an object, OpenStruct-ishly:
foo = "bar"
foo.define_attribute "baz" #=> #<Class:#<String:0x...>>
foo.baz 42 #=> 42
foo.baz #=> 42

But I digress wildly, I fear. Back to references, here's your example
worked with my above ref.rb

# Please add the following line to the top of ref.rb:
require 'delegate'

# on with the example
require 'ref'

hacker = ["bot","pen","a",5,10].map{|x|x.ref}.ref

name = hacker[0..2]
fname = name[0]
lname = name[1]
mname = name[2]

height = hacker[3..4]
feet = height[0] # I corrected an off-by one here
inches = height[1] # and here

fname[] = "Eric" # or like this: fname.ref = "Eric"
lname[] = "Mahurin"
mname[] = "?"

feet[] = 6
inches[] = 5

p name #=> ["Eric","Mahurin","?"]
p height #=> [6,5]
p hacker #=> ["Eric","Mahurin","?",6,5]