On 1/30/07, Gerald Ebberink <g.h.p.ebberink / nclr.nl> wrote:
>
> Hi all,
>
>
> I am wondering if it is possible to access the name of an instance from within a method.
> What I would like to do is something similar to this
>
> class Someclass
>
> def say_hi
>             puts "Hi I am" + self.name
> end
>
> end
>
> fun = Someclass.new
> fun.say_hi
>

This is an utter kludge and I would not recommend using it in any
production code, but here it is ... oh, and it will only work for this
very specific case :/


$ cat tmp.rb

class A
  def say_hi
    m = %r/([^:]+):(\d+)/.match caller.first
    return if m.nil?

    fn = m[1]
    num = Integer(m[2])
    line = nil

    File.open(fn,'r') do |fd|
      cnt = 0
      until fd.eof?
        cnt += 1
        l = fd.readline
        if cnt >= num
          line = l
          break
        end
      end
    end

    m = %r/(\w+)\.say_hi/.match line
    puts "Hi, I am #{m[1]}" unless m.nil?
  end
end

a = A.new
a.say_hi

b = A.new
b.say_hi


$ ruby tmp.rb
Hi, I am a
Hi, I am b


Blessings,
TwP