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
?
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.
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.
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.
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.
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)
Rails 6 now has this:
a = [1, 2, 3]
#=> [1, 2, 3]
a.extract! { |n| n.even? }
#=> [2]
a
#=> [1, 3]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With