类方法作为哈希值
我有这个工作代码:
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 } }
我收到错误消息。
是否可以使用方法作为哈希值创建哈希?
当你想要一个方法时,在Ruby中,你必须调用… method
🙂
my_hash = { :on_filter => { method(:action) } }
请注意,原始代码可能已写入:
@server.handle(&method(:action))
这告诉它使用方法action
作为块参数(这就是为什么有&
)。 相反,你传递一个块,所以为了完全等效,你现在可以传递一个块而不是一个方法,如果你愿意:
my_hash = { :on_filter => Proc.new{ action } }
当然有可能,但不完全是方法(因为方法不是Ruby中的对象),而是使用Proc
对象。 例如,看一下本教程 。
简而言之,您应该能够达到您想要的效果
my_hash = { :on_filter => Proc.new{action} }
在您的Client#initialize
。