加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在named_scope参数列表中,变量意味着什么星号

发布时间:2020-12-16 20:23:44 所属栏目:百科 来源:网络整理
导读:我有一个这样的命名范围: named_scope :by_items,lambda |*items| { :joins = :items,:conditions = ["items.id in (?)",items.map(::id)]} 什么是“*项目”是什么意思?当我用“Item.find(:first,…)”命名时,它可以正常工作.如果我尝试使用一个集合,“It
我有一个这样的命名范围:
named_scope :by_items,lambda |*items| {
  :joins => :items,:conditions => ["items.id in (?)",items.map(&::id)]
}

什么是“*项目”是什么意思?当我用“Item.find(:first,…)”命名时,它可以正常工作.如果我尝试使用一个集合,“Item.find(:all,…)”它失败.

从另一个SO问题,我知道签名应该是:

Order.by_items(item0,item1,...)

所以我的问题真的是,我如何把一个数组变成一个逗号分隔的参数列表?

UPDATE0

从Martin Fowler我学到了:

(Using a “*” in the argument list helps in working with variable arguments in ruby. In the argument list *disks indicates a vararg. I can then refer to all the disks passed in as an array named “disks”. If I call another function with “*disks” the elements of the disks array are passed in as separate arguments.)

UPDATE1

the “splat” operator更多.

解决方法

“* items”表示函数接受可变数量的参数.换句话说,如果你这样称呼:
Order.by_items(item0,item2)

命名范围lambda函数内的变量’items’将是一个有3个项目的数组.

要回答你真正的问题,你应该这样称呼:

Order.by_items(*Item.find(:all,...))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读