LoginSignup
2
1

More than 5 years have passed since last update.

nilを含んだ配列のソート

Last updated at Posted at 2018-08-20

ソートしようとしている配列にnilが含まれているとエラーとなる。

irb(main):003:0> [1,2,nil,4,5].sort
Traceback (most recent call last):
        3: from /Users/colorbox/.rbenv/versions/2.5.0/bin/irb:11:in `<main>'
        2: from (irb):3
        1: from (irb):3:in `sort'
ArgumentError (comparison of Integer with nil failed)

配列内の値にもよるがto_ito_sを利用することで安全にソート可能。

irb(main):004:0> [1,2,nil,4,5].sort { |a,b| a.to_s <=> b.to_s }
=> [nil, 1, 2, 4, 5]

もしくはcompactなどを利用しても良い

irb(main):009:0> [1,2,nil,4,5].compact.sort
=> [1, 2, 4, 5]
2
1
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
2
1