类方法作为哈希值

时间:2010-04-08 10:43:18

标签: ruby

我有这个工作代码:

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

我的服务器将处理多个操作,因此我想以这样的方式更改代码:

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

这是错误的代码,因为action()方法调用create my_hash,但是如果我尝试将代码修改为:

my_hash = { :on_filter => { action } }

我收到错误消息。

是否可以使用方法作为哈希值创建哈希?

2 个答案:

答案 0 :(得分:1)

如果你想要一个方法,在Ruby中,你必须调用... method: - )

my_hash = { :on_filter => { method(:action) } }

请注意,原始代码可能已写入:

@server.handle(&method(:action))

这告诉它使用方法action作为块参数(这就是为什么有&)。相反,你传递了一个块,所以为了完全等效,你现在可以传递一个块而不是一个方法,如果你愿意:

my_hash = { :on_filter => Proc.new{ action } }

答案 1 :(得分:0)

当然可以,但不完全是方法(因为方法不是Ruby中的对象),而是使用Proc个对象。例如,请查看this tutorial

简而言之,你应该能够达到你想要的效果

my_hash = { :on_filter => Proc.new{action} }

Client#initialize

相关问题