开发者

Improving and 'each' statement using Ruby

开发者 https://www.devze.com 2023-02-15 15:02 出处:网络
I am using R开发者_运维知识库uby on Rails 3 and I would like to improve the following code. accounts = []

I am using R开发者_运维知识库uby on Rails 3 and I would like to improve the following code.

accounts = []
ids.each { |id|
  accounts << Account.find_by_id(id)
}

puts accounts

How can I do?


If ids might have ids which don't correspond to real Accounts:

accounts = ids.map { |id| Account.find_by_id(id) }

Or if you know that all the ids will be present, you can simplify this to:

accounts = Account.find(ids)


ids.collect {|id| Account.find_by_id(id)}
0

精彩评论

暂无评论...
验证码 换一张
取 消