[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Accesing the name of an instance from within an method

Tim Pease

1/30/2007 5:15:00 PM

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

2 Answers

Gavin Kistner

1/30/2007 5:30:00 PM

0

On Jan 30, 10:15 am, "Tim Pease" <tim.pe...@gmail.com> wrote:
>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 :/
[snip]

Very tricky!

Let's make it a little shorter and more robust:
class A
def say_hi
m = %r/([^:]+):(\d+)/.match caller.first
return if m.nil?

line = IO.readlines( m[1] )[ m[2].to_i - 1 ]
return if line.nil?

puts "Hi, I am #{line[/\S+(?=.say_hi)/] || '(unknown)'}"
end
end

a = A.new
b = a
c = [ a ]
d = { :foo=>c[0] }

a.say_hi
#=> Hi, I am a

b.say_hi
#=> Hi, I am b

c[0].say_hi
#=> Hi, I am c[0]

d[:foo].say_hi
#=> Hi, I am d[:foo]

x=0
y = c[x].say_hi
#=> Hi, I am c[x]

c[x].send( :say_hi )
#=> Hi, I am (unknown)


Gavin Kistner

1/30/2007 5:33:00 PM

0

On Jan 30, 10:29 am, "Phrogz" <g...@refinery.com> wrote:
> Let's make it a little shorter and more robust:
[snip]

Oops, but my version has this result:

d[ :foo ].say_hi
#=> Hi, I am ]

Of course, the whole thing is reasonably meaningless, so it's not
surprising that this would break.