[英]Wrong number of arguments Error when using * splat operator ruby
我试图为此方法使用splat运算符,以便可以将多个参数作为菜单中的项目传递。
def place_order *items
@restaurant.receive_order(*items)
end
测试如下
it "should be able to order multiple items from menu" do
expect(user.place_order("burger", "chips")).to eq(:ordered)
end
我收到此错误...
2) User should be able to order multiple items from menu
Failure/Error: expect(user.place_order("burger", "chips")).to eq(:ordered)
ArgumentError:
wrong number of arguments (2 for 1)
我读过的所有文献都提到这是吸收多个论点的一种方式。
万一您想知道在place_order中调用的另一种方法,这就是它的外观...
def receive_order(*items)
raise "Sorry not in stock" if @menu.key?(*items) == false
@bill << items
:ordered if @menu.fetch(*items)
end
非常感谢!
问题出在您的receive_order
方法中; 是否将多个参数传递给key?
方法。 key?
方法仅接受1个参数。
@menu.key?(*items) # wrong
更改为此:
# change the "all?" to "any?" if just one will do
# if you want to check existence of key:
items.all?{ |key| @menu.has_key?(key) }
# if you want to check existence of value:
items.all?{ |val| @menu.key?(val) } # change if key can be `nil` or `false`
同样,在同一方法中,您将对具有多个参数的哈希调用fetch
,并在条件中使用返回值。 我不确定您要完成什么。
这是fetch
行为:
hash = {one: 1, two: 2}
hash.fetch(:one) #=> returns value of :one i.e. 1
hash.fetch(:two, :one) #=> seemingly returns first value found i.e. 2
hash.fetch(:three) #=> raises KeyError for absent keys
hash.fetch(:three, 3) #=> return the second passed argument if key is absent
hash.fetch(:three, 3, :four) #=> Error: wrong number of arguments (3 for 1..2)
在您的方法中,我相信您想使用fetch
检查密钥是否存在。 如果是这样,则可以实现与我在此响应开始时共享的代码相似的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.