3
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 3 years have passed since last update.

Hashの先頭からn個をとりだす

Last updated at Posted at 2020-03-19

データを抽出してchartkickに渡すHashに対し、先頭n件を抽出したかった。
helperに以下のメソッドを作成。

def chart_limit(hash, limit=5)
  # Hash[*hash.to_a.shift(limit).flatten!]
  # コメントを受けて以下に変更。
  hash.take(limit).to_h
end
利用例
hash = {"男性40代"=>13, "女性40代"=>6, "女性30代"=>5, "男性60代"=>4, "男性30代"=>4}
p chart_limit(hash, 3)
#=> {"男性40代"=>13, "女性40代"=>6, "女性30代"=>5}

ruby 2.6.5で確認済み。

参考

3
0
9

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
3
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?