Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning array without specific elements in ruby

Tags:

arrays

ruby

I looked really hard in http://www.ruby-doc.org/core-2.1.2/Array.html but I couldn't find a quick functionality to this behaviour:

arr = [1,2,3,4,5,6]

arr.without(3,6) #=> [1,2,4,5]

I know I can write my own function/monkey-patch ruby/add a class method/write it in a few lines.

Is there a way to do this in a ruby way?

like image 814
Nick Ginanto Avatar asked Jul 20 '14 08:07

Nick Ginanto


People also ask

What is an array in Ruby?

Ruby arrays are ordered, integer-indexed collections of any object. Each element in an array is associated with and referred to by an index. Array indexing starts at 0, as in C or Java.

What is a negative index in Ruby array?

Ruby - Arrays. A negative index is assumed relative to the end of the array --- that is, an index of -1 indicates the last element of the array, -2 is the next to last element in the array, and so on. Ruby arrays can hold objects such as String, Integer, Fixnum, Hash, Symbol, even other Array objects.

How to initialize an array in Ruby?

Ruby arrays can hold objects such as String, Integer, Fixnum, Hash, Symbol, even other Array objects. Ruby arrays are not as rigid as arrays in other languages. Ruby arrays grow automatically while adding elements to them. There are many ways to create or initialize an array. One way is with the new class method −

How to create an array of digits in Ruby kernel?

The Kernel module available in core Ruby has an Array method, which only accepts a single argument. Here, the method takes a range as an argument to create an array of digits − We need to have an instance of Array object to call an Array method. As we have seen, following is the way to create an instance of Array object −


3 Answers

you can use subtraction :

arr - [3,6]

EDIT

if you really wanted you could alias this method

class Array
  alias except - 
end

then you can use:

arr.except [3,6]
like image 125
Ian Kenney Avatar answered Oct 24 '22 07:10

Ian Kenney


This got added in Rails 5 :)

https://github.com/rails/rails/issues/19082

module Enumerable
  def without(*elements)
    reject { |element| element.in?(elements) }
  end
end

it's just aesthetics, but it makes sense for the brain

like image 14
Nick Ginanto Avatar answered Oct 24 '22 07:10

Nick Ginanto


There is another way using reject. But it is not cleaner than -

arr.reject{|x| [3,6].include? x}
like image 3
nishu Avatar answered Oct 24 '22 06:10

nishu