On Thu, Mar 08, 2007 at 11:36:58AM +0900, Michael Strelnikov wrote:
> >Well I tried hard with Binding.of_caller from facet but maybe I miss
> >something.
> >As I mentioned before I am not a metaprogramming guru :(
> 
> 
> :)
> 
> >Also, can I pass a "reference"/"pointer" into function?
> >Well all parameters are passed as references - even if there is a
> >studied discussion if this terminology is 100% correct.
> >
> >try e.g.
> >a="Hi there"
> >def change s
> >  s << "!!!"
> >end
> >change a
> >puts a
> >>
> >
> Probably it works with strings but try following code:
> 
> def test_change(var, val)
>    var = val
> end
> 
> myvar = 5
> test_change(myvar, 10)
> puts myvar.to_s

That's because:

(1) "<<" is a method call, but "=" is not (it's an assignment to a local
variable)

(2) Strings are mutable, but numbers are not. That is, there's no method
call you can make on the number '5' which will change its value to something
else :-)

So you either return the new number:

  def change(val)
    val + 1
  end

  myvar = 5
  myvar = change(myvar)
  puts myvar

Or you wrap it in an object:

  class Myvar
    attr_accessor :v
    def initialize(v = nil)
      @v = v
    end
    def to_s
      @v.to_s
    end
  end

  def test_change(obj, newval)
    obj.v = newval
  end

  myvar = Myvar.new(5)
  test_change(myvar, 10)
  puts myvar.to_s

The notation "attr_accessor :v" is short for:

  def v
    @v
  end

  def v=(nv)
    @v = nv
  end

So when you write obj.v = newval, you are calling v=(newval) on the object.

Regards,

Brian.