使用Liquid过滤器将数组元素设置为小写以进行排序

时间:2015-06-13 10:13:20

标签: ruby jekyll liquid

我无法弄清楚如何对包含字符串的数组进行排序: ["A", "C", "E", "b", "d"] ["A", "b", "C", "d", "E"]。{/ p>

{% assign input = "A,C,E,b,d" | split:"," %}
{{ input | join: "-" }}
{{ input | map: 'downcase' | join: "-" }}
{{ input | map: 'downcase' | sort | join: "-" }}
{{ input | map: 'length' | join: "-" }}
{{ input | map: 'size' | join: "-" }}

我对map:缺少什么?

预期产出:

A-C-E-b-d
a-c-e-b-d
a-b-c-d-e
1-1-1-1-1
1-1-1-1-1

实际输出:

A-C-E-b-d
----
----
----
----

注意:首先我尝试了map: downcase(没有引号),但没有从nil到整数的隐式转换。

2 个答案:

答案 0 :(得分:2)

好的,所以这是一个黑客,如果有人知道更好请发布另一个答案。

{% assign input = "A,C,E,b,d" | split:"," %}
{% capture intermediate %}{% for entry in input %}{{ entry | downcase }}{{ entry }}{% unless forloop.last %}{% endunless %}{% endfor %}{% endcapture %}
{% assign intermediate_sorted = intermediate | split:'' | sort %}
{% capture sorted %}{% for entry in intermediate_sorted %}{{ entry | split: '' | last }}{% unless forloop.last %}{% endunless %}{% endfor %}{% endcapture %}
{% assign sorted = sorted | split: '' %}
{{ sorted | join: "-" }}

将输出A-b-C-d-E

美国(Unit Separator\u001F,而非\u241F RS(Record Separator\u001E,不是\u241E是输入中不太可能出现的两个字符,因此可以在大多数时间安全地使用它们。如果您想要对CSS ID进行排序,则可以是,|

答案 1 :(得分:1)

file.txt filter 进行不区分大小写的排序:

sort_natural

输出{% assign my_array = "zebra, octopus, giraffe, Sally Snake" | split: ", " %} {{ my_array | sort_natural | join: ", " }}