Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete from Array and return deleted elements in Ruby

How can I delete some elements from an array and select them?

For example:

class Foo 
  def initialize
    @a = [1,2,3,4,5,6,7,8,9]
  end

  def get_a
    return @a
  end
end

foo = Foo.new
b = foo.get_a.sth{ |e| e < 4 }
p b # => [1,2,3]
p foo.get_a # => [4,5,6,7,8,9,10]

What I can use instead of foo.get_a.sth?

like image 842
NewMrd Avatar asked Jul 31 '13 14:07

NewMrd


People also ask

What does .shift do in Ruby?

The shift() is an inbuilt function in Ruby returns the element in the front of the SizedQueue and removes it from the SizedQueue. Parameters: The function does not takes any element. Return Value: It returns the first element which is at the front of the SizedQueue and removes it from the SizedQueue.

What does .select do in Ruby?

Array#select() : select() is a Array class method which returns a new array containing all elements of array for which the given block returns a true value. Return: A new array containing all elements of array for which the given block returns a true value.

What does .POP do in Ruby?

The pop() function in Ruby is used to pop or remove the last element of the given array and returns the removed elements. Parameters: Elements : This is the number of elements which are to be removed from the end of the given array.

What does .first mean in Ruby?

Ruby | Array class first() function first() is a Array class method which returns the first element of the array or the first 'n' elements from the array.


2 Answers

If you don't need to retain the object id of a:

a = [1,2,3,4,5,6,7,8,9,10]
b, a = a.partition{|e| e < 4}
b # => [1, 2, 3]
a # => [4, 5, 6, 7, 8, 9, 10]

If you do need to retain the object id of a, then use a temporal array c:

a = [1,2,3,4,5,6,7,8,9,10]
b, c = a.partition{|e| e < 4}
a.replace(c)
like image 65
sawa Avatar answered Oct 08 '22 16:10

sawa


Rails 6 now has this:

a = [1, 2, 3]
#=> [1, 2, 3]
a.extract! { |n| n.even? }
#=> [2]
a
#=> [1, 3] 
like image 34
Mirror318 Avatar answered Oct 08 '22 17:10

Mirror318