Dispatching a function based on a message

E

Edgardo Hames

I'm back writing my small network app (IM client) and I need to
dispatch functions based on the messages received from the server. For
example, if my app gets a string like

MSG msg_number som_other_text

it should call the function process_MSG and pass some_other_text as an argument.

How can I do that? I was thinking of a big case statement, but I'm not
sure that's the Ruby Way. Probably a hash with MSGs as keys and
process_MSGs as values?

Thanks for your ideas,
Ed
 
M

Mark Sparshatt

--- Edgardo Hames said:
I'm back writing my small network app (IM client)
and I need to
dispatch functions based on the messages received
from the server. For
example, if my app gets a string like

MSG msg_number som_other_text

it should call the function process_MSG and pass
some_other_text as an argument.

How can I do that? I was thinking of a big case
statement, but I'm not
sure that's the Ruby Way. Probably a hash with MSGs
as keys and
process_MSGs as values?

You could try using the send method

class MyClass
def process_MSG(val)
#do something
end
end

if you've split the message up into the variables msg,
msg_number, other_text then you'd just need to do

processor = MyClass.new
processor.send("process_#{msg), other_text)

HTH

--
Mark Sparshatt








___________________________________________________________
ALL-NEW Yahoo! Messenger - all new features - even more fun! http://uk.messenger.yahoo.com
 
R

Robert Klemme

Mark Sparshatt said:
You could try using the send method

class MyClass
def process_MSG(val)
#do something
end
end

if you've split the message up into the variables msg,
msg_number, other_text then you'd just need to do

processor = MyClass.new
processor.send("process_#{msg), other_text)

HTH

We can even wrap that:

class MyClass
def process_MSG(val) ... end

def receive(line)
if /\A(\S+)\s+\d+\s+(.*)\Z/ =~ line
send($1,$2)
end
end
end

Kind regards

robert
 

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
474,166
Messages
2,570,907
Members
47,448
Latest member
DeanaQ4445

Latest Threads

Top