【问题标题】:how to sort alphabetically in ruby如何在ruby中按字母顺序排序
【发布时间】:2020-03-03 02:40:51
【问题描述】:

我有此代码,我在其中执行 .each_slice(2),然后我想按字母顺序 sort,但仅在之后添加排序不起作用,to_a.sort 也不起作用:

.form-group__container
  .form-group__row
    - Algorithm.where(filterable: 'true').each_slice(2).sort do |algorithms|
      .form-group__col
        - algorithms.each do |algorithm|

谁能告诉我它是如何在 ruby​​ on rails 中完成的?

【问题讨论】:

  • each_slice(2) 创建大小为 2 的子数组。您是否要对这些子数组进行排序?如果是这样,你想按什么排序?
  • @dimanyc 我正在尝试对例如 ex 的列表进行排序。 [“google”、“bing”、“msn”、“apple”、“microsoft”]
  • Algorithm.where(filterable: 'true').each_slice(2) 返回一个 Enumerator obj,如下所示:[[#<Algorithm id: 1, name: "mergesort"], #<Algorithm id: 2, name: "dijkstra"], [..and so on]]。如果你想通过最后一行的name attr 对子数组进行排序,而不是algorithms.each do |algo|,你可以使用algorithms.sort_by(&:name) do |algo|
  • 我收到语法错误both block arg and actual block given
  • 哎呀。错字。这样做:algorithms.sort_by(&:name).each do |algo|

标签: ruby-on-rails ruby haml


【解决方案1】:

在@dimanyc 的帮助下,我的问题的解决方案如下所示:

- Algorithm.where(filterable: 'true').sort_by(&:name).each_slice(2) do |algorithms|

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 2018-09-15
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    相关资源
    最近更新 更多