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?

More than 1 year has passed since last update.

【Ruby】ハッシュの値でreduceする

Posted at

HashのValueをreduceしたい際に迷ったためメモ。

結論

hash = {
  hoge1: 10,
  hoge2: 20,
  hoge3: 30
}

# 第二引数を (key, value) で渡す
hash.reduce(0) do |acc, (_, number)|
  acc + number
end
# => 60

第二引数に一つだけ渡してみた場合

key → value → key → ... と交互に繰り返し処理が行われる

hash.reduce([]) do |acc, item|
  acc + item
end
# => [:hoge1, 10, :hoge2, 20, :hoge3, 30] keyとvalueが交互に配列に格納された

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?