Skip to content

Instantly share code, notes, and snippets.

@yyalim
Created August 5, 2014 17:48
Show Gist options
  • Save yyalim/445e624e5b195a0fdd42 to your computer and use it in GitHub Desktop.
Save yyalim/445e624e5b195a0fdd42 to your computer and use it in GitHub Desktop.
# Title is an active record model
titles = Title.all.each { |title| title.some_attribute = Random.new_seed }.sort_by { |title| title.some_attribute }
@proxygear
Copy link

Your code works, the only problem is : your loop 2 times on the array.
You may want to avoid it with this tricks:

# Ensure that item has some_attribute value and return this value
def ensure_item_some_attr item
  item.some_attribute ||= Random.new_seed
end
# Sort items, and at the same time, set value to items that don't have
titles = Title.all.sort {|x, y| ensure_item_some_attr(x) <=> ensure_item_some_attr(y) }

But it's really not a nice code, not really explicit ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment