Search code examples
ruby-on-railsruby-on-rails-4cycle

Get succeeding object in cycled collection


I have a collection of users which is ordered by their last name.

User.order(last_name: :asc)

I want to get the user suceeding another one (stored in variable), and if last in collection get the first.

Any better solutions to this than what I've done?

user # stored user object
users = User.order(last_name: :asc)
index = users.index {|item| item == user}
succeeding = if user == users[index].last then users[index].first else users[index + 1] end

Solution

  • user # stored user object
    users = User.order(last_name: :asc)
    
    succeeding = users[users.find_index(user)+1]||users.first