class method as hash value

Posted by demas on Stack Overflow See other posts from Stack Overflow or by demas
Published on 2010-04-08T10:43:17Z Indexed on 2010/04/08 10:53 UTC
Read the original article Hit count: 213

Filed under:

I have this working code:

class Server
  def handle(&block)
    @block = block
  end

 def do
   @block.call
 end
end

class Client
  def initialize
    @server = Server.new
    @server.handle { action }
  end

  def action
    puts "some"
  end

  def call_server
    @server.do
  end
end

client = Client.new
client.call_server

My Server will handle more then one action so I want to change code such way:

class Server
  def handle(options)
    @block = options[:on_filter]
 end

 def do
   @block.call
 end
end

class Client
  def initialize
    @server = Server.new

   my_hash = { :on_filter => action }
   @server.handle(my_hash)
  end

  def action
    puts "some"
  end

  def call_server
    @server.do
  end
end

client = Client.new
client.call_server

It is incorrect code because action() method calls on create my_hash, but if I try to modify code to:

my_hash = { :on_filter => { action } }

i get error message.

Is it possible to create hash with methods as hash values ?

© Stack Overflow or respective owner

Related posts about ruby