48986aabbdbcdeacdbc3a6dc2945a9ff

There are some elements in an array, e.g. users, and I have a user_id, move the user which user.id == user_id to the first place.

user_id = xx
users = [....]

user = users.delete(users.detect {|u| u.id == user_id})
users.unshift(user)

Refactorings

No refactoring yet !

42508426a0b6431ebdc3c2aa05e33503

sean

July 6, 2011, July 06, 2011 07:31, permalink

No rating. Login to rate!

Not sure why you need the detect, since you already have the key. Is it possible the key isn't already in the array?

users.unshift(users.delete(user_id))
42508426a0b6431ebdc3c2aa05e33503

sean

July 6, 2011, July 06, 2011 07:31, permalink

No rating. Login to rate!

Not sure why you need the detect, since you already have the key. Is it possible the key isn't already in the array?

users.unshift(users.delete(user_id))
42508426a0b6431ebdc3c2aa05e33503

sean

July 6, 2011, July 06, 2011 07:32, permalink

No rating. Login to rate!

Not sure why you need the detect, since you already have the key. Is it possible the key isn't already in the array?

users.unshift(users.delete(user_id))
48986aabbdbcdeacdbc3a6dc2945a9ff

Fred Liang

July 6, 2011, July 06, 2011 07:44, permalink

No rating. Login to rate!

Thanks sean, but the element type is User instead of integer

users.first.class
# => User

user_id.class
# => Fixnum

users.delete(user_id)
# => nil
48986aabbdbcdeacdbc3a6dc2945a9ff

Fred Liang

July 6, 2011, July 06, 2011 07:44, permalink

No rating. Login to rate!

Thanks sean, but the element type is User instead of integer

users.first.class
# => User

user_id.class
# => Fixnum

users.delete(user_id)
# => nil
A8d3f35baafdaea851914b17dae9e1fc

Adam

July 6, 2011, July 06, 2011 08:43, permalink

No rating. Login to rate!

If User happens to be an ActiveRecord class:

class User < ActiveRecord::Base
  def self.promote(id)
    # A bound variable would be preferred here, but doesn't seem to be supported by the MySQL adapter.
    # I would recommend sanitizing id for real-world usage.
    order("id = #{id} DESC")
  end
end

User.promote(user_id)

Your refactoring





Format Copy from initial code

or Cancel