简体   繁体   中英

Most Efficient Way to Sort By String, Based on Defined Array in Ruby on Rails

I am trying to find the most efficient way to sort an array based on a defined order from another array and display it in my presenter. There is a property of the array that needs sorting, that I want to sort on, 'name'. So there is a function, 'dogs_available' that returns a collection of objects that looks like:

[{name:'Timmy', size:'small', eyes:'brown'},{name:'Rico', size:'large', eyes:'purple'}]

So I want

sort_order = ['Timmy', 'Charlie', 'Rico', 'Hannah']
m.dogs_available.sort do |x,y|
  x = sort_order.index x.name
  y = sort_order.index y.name
  if x.nil?
    -1
  elsif y.nil?
    -1
  else
    x <=> y
  end
end

And then to print it out (just for testing, I'll clean it up later) it looks like:

dogs = m.dogs_available
text = ""
dogs.each do |dog|
  text += "<h4>#{dog.name}</h4>"
end
text.html_safe

For starters, this sort doesn't work. Also, I am confident this isn't the best way to sort/compare. Any pointers?

Your existing sort logic can be replaced with

m.dogs_available.sort_by{|hash| sort_order.index(hash[:name]) || -1}

however, where is dogs_available coming from? Usually in rails you'd be pulling data out of the database, and you can do your sorting then.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM