user_id = xx
users = [....]
user = users.delete(users.detect {|u| u.id == user_id})
users.unshift(user)
Refactorings
No refactoring yet !
sean
July 6, 2011, July 06, 2011 07:31, permalink
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))
sean
July 6, 2011, July 06, 2011 07:31, permalink
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))
sean
July 6, 2011, July 06, 2011 07:32, permalink
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))
Fred Liang
July 6, 2011, July 06, 2011 07:44, permalink
Thanks sean, but the element type is User instead of integer
users.first.class # => User user_id.class # => Fixnum users.delete(user_id) # => nil
Fred Liang
July 6, 2011, July 06, 2011 07:44, permalink
Thanks sean, but the element type is User instead of integer
users.first.class # => User user_id.class # => Fixnum users.delete(user_id) # => nil
Adam
July 6, 2011, July 06, 2011 08:43, permalink
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)
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.