jRuby / Rails 按另一个哈希值对哈希进行排序
我有一个哈希,它将根据特定变量以不同的方式呈现我的 html。该变量位于哈希值内。所以我想知道如何将哈希值传递给分组依据。对其余的内容进行排序是我正在尝试的,也许这会比我的措辞更好地解释它。
<% grouped = svcs.group_by { |svc| svc[val[:sorttype]] } %>
val 是多维哈希。前 2 个键值对 sorttype 和另一个是简单的键和值,第三部分 (svcs) 包含 2D 哈希的等效项。如果我手动输入我想要应用于该组的排序类型,即:
<% grouped = svcs.group_by { |svc| svc[:service_name] } %>
在 PHP 中,我知道在类似的实例中,我可以将某种变量传递给类似的东西并让它工作。我想这里就是这种情况。但是我不确定如何放入变量。因为我尝试过的所有方法都不起作用
I have a hash that will render my html differently based on a particular variable. The variable is within the hash. So I am wondering how I can pass a hash value to a group by. to sort the rest heres what I am trying, maybe this will explain it better than me wording it.
<% grouped = svcs.group_by { |svc| svc[val[:sorttype]] } %>
val is a multidimensional hash. the first 2 key value pairs sorttype and one other are simple key and value, the 3rd piece (svcs) contains the equivilent of a 2D hash. Which if I manually type the type of sort I want to apply to it for the group by it works ie:
<% grouped = svcs.group_by { |svc| svc[:service_name] } %>
in PHP i know in a similar instance I can pass a variable of some sort to something like this and have it work. I assume such is the case here. However Im not sure how to put the variable in. Cause all the ways Ive tried don't work
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这取决于一点。
Rails 有一个
HashWithIn DifferentAccess
,它不会区分字符串和符号键;如果您使用其中之一,它应该按原样工作。如果不是,则取决于
val
条目是什么 - 如果它们是字符串,请使用to_sym
转换为符号,例如svc[val[:排序类型].to_sym]
。It depends a little.
Rails' has a
HashWithIndifferentAccess
that will not distinguish between string and symbol keys; if you're using one of those, it should work as-is.If it's not, it depends what the
val
entries are--if they're strings, convert to a symbol usingto_sym
, e.g.,svc[val[:sorttype].to_sym]
.