我有一个数组中的名称列表,例如:
['John', 'Smith', 'Doe', 'Lee', 'Jack']
我希望它像这样分组:
['Doe']
['Jack', 'John']
['Lee']
['Smith']
我如何使用 ruby on rails 做到这一点?
最佳答案
可枚举的 group_by
是你的 friend :
names = ['John', 'Smith', 'Doe', 'Lee', 'Jack']
names.group_by{ |n| n[0] }
# => {"J"=>["John", "Jack"], "S"=>["Smith"], "D"=>["Doe"], "L"=>["Lee"]}
names.group_by{ |n| n[0] }.values
# => [["John", "Jack"], ["Smith"], ["Doe"], ["Lee"]]
来自文档:
Groups the collection by result of the block. Returns a hash where the keys are the evaluated result from the block and the values are arrays of elements in the collection that correspond to the key.
如果您想按字母顺序排列它们,只需在使用 group_by
之前对初始数组进行排序。因为 Ruby 维护哈希的插入顺序,所以哈希的结果值也将按顺序排列:
names.sort.group_by{ |n| n[0] }.values
# => [["Doe"], ["Jack", "John"], ["Lee"], ["Smith"]]
关于ruby-on-rails - ruby rails : How to group list of names based on the initial?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20063996/