Idiom -- is there a better way?

M

Mark Probert

Hi ..

I am doing indirect dispatch, something like:

class Foo
def bar(fn)
eval "self.#{fn}"
end
end

class Bar < Foo
def blah
puts "blah here"
end
end

f = Bar.new
f.bar("blah")

It works however I am sure there must be a nicer way of doing the bar(fn)
stuff. Any ideas?

TIA,
-mark.
 
T

trans. (T. Onoma)

On Wednesday 20 October 2004 12:54 pm, Mark Probert wrote:
| Hi ..
|
| I am doing indirect dispatch, something like:
|
| class Foo
| def bar(fn)
self.send(fn)
| end
| end
|
| class Bar < Foo
| def blah
| puts "blah here"
| end
| end
|
| f = Bar.new
| f.bar("blah")
|
| It works however I am sure there must be a nicer way of doing the bar(fn)
| stuff. Any ideas?
|
| TIA,
| -mark.

--
( o _ カラãƒ
// trans.
/ \ (e-mail address removed)

I don't give a damn for a man that can only spell a word one way.
-Mark Twain
 
G

Gavin Kistner

class Foo
def bar(fn)
eval "self.#{fn}"
end
end

class Bar < Foo
def blah
puts "blah here"
end
end

f = Bar.new
f.bar("blah")

Does the function need to be a string argument?

f.bar( f.method( :blah ) ) # Pass the actual method reference

or, as others have noted:

class Foo
def bar( meth_name )
self.method(m).call
end
end
...
f.bar( :blah )
 
R

Robert Klemme

Mark Probert said:
Hi ..

I am doing indirect dispatch, something like:

class Foo
def bar(fn)
eval "self.#{fn}"
end
end

class Bar < Foo
def blah
puts "blah here"
end
end

f = Bar.new
f.bar("blah")

It works however I am sure there must be a nicer way of doing the bar(fn)
stuff. Any ideas?

TIA,
-mark.

There's no need for method bar because that is built into Ruby alread:
Object#send does the job:

class Bar
def blah
puts "blah here"
end
end

blah here
=> nilblah here
=> nil
Kind regards

robert
 
M

Mark Probert

Hi ..

Gavin Kistner said:
Does the function need to be a string argument?

Yup. What I am doing is taking a YAML entry and converting it into a
method call for a derived class.

Thanks to all for the help.
 
J

John Carter

#On Thu, 21 Oct 2004, Mark Probert wrote:
#
#Try

class Foo
def bar(fn)
send(fn)
end
end

class Bar < Foo
def blah
puts "blah here"
end
end

f = Bar.new
f.bar:)blah)




#
#John Carter Phone : (64)(3) 358 6639
#Tait Electronics Fax : (64)(3) 359 4632
#PO Box 1645 Christchurch Email : (e-mail address removed)
#New Zealand
#
# ruby -wc certifies this email "Syntax OK"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top