Project

General

Profile

Actions

Feature #15111

closed

Make the number of arguments of `Hash#merge` variable

Added by liwii (Koki Ryu) about 3 years ago. Updated about 3 years ago.

Status:
Closed
Priority:
Normal
Target version:
-
[ruby-core:88970]

Description

Abstract

Make the number of arguments of Hash#merge variable.

Background

In many websites such as Stack Overflow and Qiita, many people are seeking how to merge more than three hashes.

https://stackoverflow.com/questions/19548496/how-to-merge-multiple-hashes-in-ruby
https://qiita.com/hc0208/items/c662f5189fa383872f4e
https://stackoverrun.com/ja/q/4997431

Many ways, like using Enumerable#inject or calling Hash#merge multiple times, are proposed, but both don't seem intuitive. Especially when using block in Hash#merge, the code becomes too complicated.

Proposal

Change the argument of Hash#merge from singular to variable length.

Implementation

https://github.com/ruby/ruby/pull/1951

Evaluation

The code to merge more than three hashes became much simpler and more intuitive.

before

hash1.merge(hash2).merge(hash3)

[hash1, hash2, hash3].inject do |result, part|
  result.merge(part) { |key, value1, value2| key + value1 + value2 }
end

after

hash1.merge(hash2, hash3)
hash1.merge(hash2, hash3) { |key, value1, value2| key + value1 + value2 }

Discussion

Summary

The change is needed to make Hash#merge more useful and intuitive.

Actions

Also available in: Atom PDF