0

I am aware of the following two methods to remove items from array:

a.delete_if {|x| x >= "b" } 
array.reject {|x| x < 3}

But neither of them suite my needs. I need a way to specify a clean way to identify the items to remove from the array. Something like this:

Model.column_names # => [:age, :name, :created_at, :updated_at]
Model.column_names.discard :created_at, :updated_at
Model.column_names # => [:age, :name]

where discard could take an unlimited amount of symbols.

3
  • You need it, but you haven't showed us that you've tried to write it. That makes it sound like you're fishing for someone else to write it for you. Instead, show us what you've tried and describe why it didn't work. Commented Aug 29, 2014 at 19:56
  • @theTinMan I could easily make my own such method, but I was anticipating something already built in, such as "-=" below. Commented Aug 29, 2014 at 20:31
  • That may be, however, on Stack Overflow, by consensus, it's agreed that questions should show what has been tried previously, which helps rule out those "feed me code" questions. Commented Aug 31, 2014 at 0:14

2 Answers 2

4

How about?

Model.column_names # => [:age, :name, :created_at, :updated_at]
Model.column_names -= [:created_at, :updated_at]
Model.column_names # => [:age, :name]
Sign up to request clarification or add additional context in comments.

1 Comment

That is correct. - and + are overloaded for arrays to append and remove items respectively.
1

There is this way with reject...

Model.column_names.reject {|x| [:created_at, :updated_at].include?(x) }

Another way would be with select...

Model.column_names.select {|x| not [:created_at, :updated_at].include?(x) }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.