Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reposition an element to the front of an array in Ruby

Tags:

Even coming from javascript this looks atrocious to me:

irb >> a = ['a', 'b', 'c'] => ["a", "b", "c"] >> a.unshift(a.delete('c')) => ["c", "a", "b"] 

Is there a more legible way placing an element to the front of an array?

Edit my actual code:

if @admin_users.include?(current_user)   @admin_users.unshift(@admin_users.delete(current_user)) end 
like image 238
methodofaction Avatar asked Oct 03 '12 18:10

methodofaction


People also ask

How do you change the position of an element in an array?

To change the position of an element in an array:Use the splice() method to insert the element at the new index in the array. The splice method changes the original array by removing or replacing existing elements, or adding new elements at a specific index.

How do you push an element to an array in Ruby?

Ruby | push() function The push() function in Ruby is used to push the given element at the end of the given array and returns the array itself with the pushed elements. Parameters: Elements : These are the elements which are to be added at the end of the given array. Returns: the array of pushed element.

What does .first do in Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.


1 Answers

Maybe this looks better to you:

a.insert(0, a.delete('c')) 
like image 193
Mark Thomas Avatar answered Sep 28 '22 04:09

Mark Thomas