Project

General

Profile

Actions

Feature #16104

open

Introduce merge_if and merge_if!

Added by akash (Akash Gupta) over 5 years ago. Updated over 5 years ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:94354]

Description

The method merge_if / merge_if will merge the passed hash in parameter only if the block evaluates to true, otherwise not. Similar to count method with a block.

Updated by akash (Akash Gupta) over 5 years ago

akash (Akash Gupta) wrote:

The method merge_if / merge_if! will merge the passed hash in parameter only if the block evaluates to true, otherwise not. Similar to count method with a block.

For ex:

a = {a: 'Apple'}
a.merge_if(b: 'Ball') {|k, v| v == 'Apple'}
=> {a: 'Apple', b: 'Ball'}

Updated by shevegen (Robert A. Heiler) over 5 years ago

Hmmm. I have mixed feelings about it. I think being able to add something
into e. g. a Hash, based on a conditional inside of the method, may be useful.

We also have at the least one example of "_if", such as for Array:

.delete_if

Where (I think) this may be equal to Array#reject!.

There is no .delete_if! though, so perhaps this may apply to your feature
request too.

On the other hand ... visually I am not entirely sure whether this is
quite elegant, although this is highly subjective.

Consider:

if foobar
  barfoo.merge_if(b: 'Ball') {|k, v| v == 'Apple'}
end unless blub

This is of course contrived, but the part I am unsure is whether we should
have more NAME_if methods as such. I can not say whether I am completely
against it, but I am a bit wary of such method names that include conditionals
in the name itself.

I think most ruby names tend to be one word; a few are two words.

(If anyone knows of more methods that have "_if" as part of their names,
in core/stdlib, please feel free to add to the list - I really do not know
of more examples off the top of my head.)

PS: On a side note, I never manage to remember the difference between .merge()
.merge!() and .update() off-hand - I always try in irb first; I only know one
is an alias ... :D

Updated by sawa (Tsuyoshi Sawada) over 5 years ago

Do

a.each_with_object(b: 'Ball') {|(k, v), h| h[k] = v if v == 'Apple'}

or

{b: 'Ball'}.merge(a.select{|k, v| v == 'Apple'})

Updated by janfri (Jan Friedrich) over 5 years ago

akash (Akash Gupta) wrote:

The method merge_if / merge_if! will merge the passed hash in parameter only if the block evaluates to true, otherwise not. Similar to count method with a block.

What if the callee has more than one entry? For example

a = {a: 'Apple', c: 'Pear'}
a.merge_if(b: 'Ball') {|k, v| v == 'Apple'}
# => ???

The block is called twice and evaluates one time to true and the other time to false.

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0