0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Ruby】each_with_objectを使うと便利だよって話

Last updated at Posted at 2022-02-18

each_with_objectを使う方と使わない方で同じ結果になる。
each_with_objectを使う方が1行コードを減らせるし、すっきりして見やすいのでeach_with_objectを積極的に使っていきたい。

##each_with_objectを使わない①

users = User.all
posts = []
users.each do |user|
  posts << user.posts
end

##each_with_objectを使わない②

users = User.all
posts = users.map(&:posts)
#> posts
#=> [[#<Post:0x00007f01540e45a0
   id: 303,
   content: "内容内容内容内容内容内容",
   created_at: Fri, 18 Feb 2022 11:41:52.844699000 JST +09:00,
   updated_at: Fri, 18 Feb 2022 11:41:52.844699000 JST +09:00>],
 [#<Post:0x00007f0154482540
   id: 304,
   content: "内容内容内容内容内容内容",
   created_at: Fri, 18 Feb 2022 11:41:53.312786000 JST +09:00,
   updated_at: Fri, 18 Feb 2022 11:41:53.312786000 JST +09:00>]]

##each_with_objectを使う

users = User.all
posts = users.each_with_object([]) do |user, array|
  array << user.posts
end

#> posts
#=> [[#<Post:0x00007f01540e45a0
   id: 303,
   content: "内容内容内容内容内容内容",
   created_at: Fri, 18 Feb 2022 11:41:52.844699000 JST +09:00,
   updated_at: Fri, 18 Feb 2022 11:41:52.844699000 JST +09:00>],
 [#<Post:0x00007f0154482540
   id: 304,
   content: "内容内容内容内容内容内容",
   created_at: Fri, 18 Feb 2022 11:41:53.312786000 JST +09:00,
   updated_at: Fri, 18 Feb 2022 11:41:53.312786000 JST +09:00>]]

##参考

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?