LoginSignup
0
0

More than 5 years have passed since last update.

条件で一番多い配列を取り出す。

Posted at

配列の中から一番多いを取り出す。

0,1,2で一番多い配列は?
m = [[0, 0, 0, 0], [1, 1, 12, 2], [4, 5, 6, 4, 3], [2]]
m.max_by{|i|i.count(0)} => [0, 0, 0, 0]
m.max_by{|i|i.count(1)} => [1, 1, 12, 2]
m.max_by{|i|i.count(2)} => [1, 1, 12, 2]

数が同じ場合は、先頭の配列が呼び出される。

m = [[0, 0, 0, 0], [1, 1, 12, 2], [4, 5, 6, 4, 3], [2]]
m.max_by{|i|i.size} => [4, 5, 6, 4, 3]

a=["abc","abcd","abcde"]
a.max_by{|i|i.size} => "abcde"

配列や文字列の長さも取り出せる。

0
0
1

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