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?

Ruby sort_by でソートの基準を設定

Posted at

はじめに

本記事はRuby初心者が備忘録として作成したものとなっております。間違い等ありましたら、指摘していただけると幸いです。

sort_byメソッドとは?

ソートの基準を自由に設定するができ、より複雑なコレクションの並び替えが可能になる。
sort、sort_byはどちらも配列をソートするメソッドですがsort_byのほうが処理が速いそうです。

Ruby
books = [
  {name: "Book2",price:1000},
  {name: "Book1",price:500},
  {name: "Book3",price:2000}
  ]

sort_book = books.sort_by{ |book| [book[:price],book[:name]] }

puts sort_book

【実行結果】

{:name=>"Book1", :price=>500}
{:name=>"Book2", :price=>1000}
{:name=>"Book3", :price=>2000}

降順ソートをしたい場合は - をつける

Ruby
books = [
  {name: "Book2",price:1000},
  {name: "Book1",price:500},
  {name: "Book3",price:2000}
  ]

sort_book = books.sort_by{ |book| [-book[:price],book[:name]] } 本のpriceを降順ソートしたいのでbook[:price]に - をつける

puts sort_book

【実行結果】
{:name=>"Book3", :price=>2000}
{:name=>"Book2", :price=>1000}
{:name=>"Book1", :price=>500}

参考元

https://docs.ruby-lang.org/ja/latest/method/Enumerable/i/sort_by.html
https://qiita.com/hayato0311/items/52a2eac88545fcaff139
https://style.potepan.com/articles/30459.html

0
0
0

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?