Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

複数の配列にeachメソッドを使いたい

More than 1 year has passed since last update.

rubyのzipメソッドを使えば可能

Ruby 2.7.0 リファレンスマニュアルよりサンプルコードを引用

p [1,2,3].zip([4,5,6], [7,8,9])
    # => [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

p [1,2].zip([:a,:b,:c], [:A,:B,:C,:D])
    # => [[1, :a, :A], [2, :b, :B]]

p [1,2,3,4,5].zip([:a,:b,:c], [:A,:B,:C,:D])
    # => [[1, :a, :A], [2, :b, :B],
    #     [3, :c, :C], [4, nil, :D], [5, nil, nil]]

p [1,2,3].zip([4,5,6], [7,8,9]) {|ary|
  p ary
}
    # => [1, 4, 7]
    #    [2, 5, 8]
    #    [3, 6, 9]
    #    nil

参考

https://docs.ruby-lang.org/ja/latest/method/Array/i/zip.html

https://freesworder.net/ruby-each-multiple/

kashiwamochi_ruby_rails
2020年夏から業務開始の駆け出しエンジニア 業務で使用: Vue.js / Nuxt.js / Laravel / Docker 独学: Ruby / Rails
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away