Skip to content

Add Array#add to push and return item #13009

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

aviflombaum
Copy link

Adds an item to an array and returns the added item and not the array itself.

a = [1, 2, 3]
a.add(4) #=> 4
a #=> [1, 2, 3, 4]

Useful to avoid patterns like:

# ❌
def add_message(message)
  messages << message
  message
end

# ✅
def add_message(message)
  messages.add(message)
end

This comment has been minimized.

Copy link
Member

@nobu nobu left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To add a new feature, we need discussion at https://bugs.ruby-lang.org.

#
# Related: see {Methods for Assigning}[rdoc-ref:Array@Methods+for+Assigning].
def add item
item.tap { push(it) }
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why using unnecessary tap?

Suggested change
item.tap { push(it) }
self << item
item

or, to avoid side effects by redefinition of other Array methods:

Suggested change
item.tap { push(it) }
Primitive.cexpr!(%q{rb_ary_push(self, item)})
item

Copy link
Member

@nobu nobu left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mistake.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

2 participants