Sort hash by key, return hash in Ruby

前端 未结 10 1457
时光取名叫无心
时光取名叫无心 2020-11-27 10:05

Would this be the best way to sort a hash and return Hash object (instead of Array):

h = {\"a\"=>1, \"c\"=>3, \"b\"=>2, \"d\"=>4}
# => {\"a\"=         


        
10条回答
  •  旧时难觅i
    2020-11-27 10:45

    I had the same problem ( I had to sort my equipments by their name ) and i solved like this:

    <% @equipments.sort.each do |name, quantity| %>
    ...
    <% end %>
    

    @equipments is a hash that I build on my model and return on my controller. If you call .sort it will sort the hash based on it's key value.

提交回复
热议问题