[英]Sort_by in Hash - reverse or not reverse - how?
I have the hash, below: 我有哈希,如下:
library = {"1"=>{"title"=>"bbb", "money"=>10}, "2"=>{"title"=>"aaa", "money"=>12}}
and my application_helper.rb: 和我的application_helper.rb:
def sortable_columns
%w[title money]
end
def sort_column
sortable_columns.include?(params[:column]) ? params[:column] : "title"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
def sort_link(column, title)
direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
icon = sort_direction == "asc" ? "fa fa-arrow-down" : "fa fa-arrow-up"
icon = column == sort_column ? icon : ""
link_to "#{title} <i class='#{icon}'></i>".html_safe, {column: column, direction: direction}
end
My table in table.html.erb: 我在table.html.erb中的表:
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<% sortable_columns.each do |column| %>
<th><%= sort_link column, column %></th>
<% end %>
</tr>
</thead>
<tbody>
<% library.sort_by {|k| k[1][sort_column]}.each_with_index do |data, i| %>
...
<% end %>
</tbody>
</table>
and now - after click in "title" or "money" header - table's sorting ASC. 现在 - 点击“title”或“money”标题后 - 表格的排序ASC。 I would like it to display DESC when clicked again (with icon arrow-down). 我想再次点击时显示DESC(带箭头向下)。 How can this be done? 如何才能做到这一点? I thought about "reverse", after library.sort_by {|k| k[1][sort_column]}
在library.sort_by {|k| k[1][sort_column]}
之后,我想到了“反向” library.sort_by {|k| k[1][sort_column]}
, but doesn't work. library.sort_by {|k| k[1][sort_column]}
,但不起作用。
Reverse does work: 反向确实有效:
library = {"1"=>{"title"=>"bbb", "money"=>10}, "2"=>{"title"=>"aaa", "money"=>12}}
sort_column = "money"
sort_direction = "asc"
library
.sort_by {|k| k[1][sort_column]}
.tap { |l| l.reverse! if sort_direction == "desc" }
# => [["1", {"title"=>"bbb", "money"=>10}], ["2", {"title"=>"aaa", "money"=>12}]]
sort_direction = "desc"
library
.sort_by {|k| k[1][sort_column]}
.tap { |l| l.reverse! if sort_direction == "desc" }
# => [["2", {"title"=>"aaa", "money"=>12}], ["1", {"title"=>"bbb", "money"=>10}]]
you can sory hash as per below 你可以按照下面的方式使用sory hash
if sort by only title then 如果只按标题排序那么
library.values.sort_by{|h| h["title"] }
or you want to sort by first title and second money then use 或者你想按第一个标题和第二个钱排序然后使用
library.values.sort_by{|h| [h["title"], h["money"]] }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.