1

I want to define a method_missing function for one of my classes, and I want to be able to pass in a hash as the argument list instead of an array. Like this:

MyClass::get_by_id {:id => id}
MyClass::get_by_id {:id => id, :filters => filters}
MyClass::get_by_id {:id => id, :filters => filters, :sort => sort}

As far as I can tell, the args list gets passed in as an array, so keys get dropped and there's no way to tell which arguments is which. Is there a way to force Ruby to treat the argument list in method_missing as a hash?

4

3 回答 3

3

你有什么问题?这对我有用:

class MyClass
  def self.method_missing name, args
    puts args.class
    puts args.inspect
  end
end

MyClass.foobar :id => 5, :filter => "bar"
# Hash
# {:id=>5, :filter=>"bar"}
于 2013-09-16T19:23:20.550 回答
1

这是你想要的 ?

class Foo
    def self.method_missing(name,*args)
        p args
        p name
    end
end

Foo.bar(1,2,3) 
# >> [1, 2, 3]
# >> :bar
于 2013-09-16T18:21:58.560 回答
0

我正在根据我自问以来所做的实验来回答我自己的问题。在 arg 列表上使用哈希 splat 时,您可以像这样传入哈希:

MyClass::get_by_id(:id => id, :filters => filters)

参数列表将如下所示:

[
  {
    :id => id,
    :filters => filters
  }
]

Ruby 将键/值对放入位置 args[0] 的单个散列对象中。如果你这样调用方法:

MyClass::get_by_id(id, :filters => filters)

您的参数列表将是这样的:

[
  id,
  {:filters => filters}
]

所以基本上,键/值对被合并成一个散列并按顺序传递。

于 2013-09-16T19:25:42.223 回答