繁体   English   中英

Ruby按对象的字符串首字符对数组进行排序

[英]Ruby sort array with objects by first character of string

这是我第一次尝试使用ruby,这可能是一个简单的问题,我被困了一个小时,我有一个ruby数组,其中包含一些对象,并且我希望该数组按对象名称中的第一个字符进行排序属性(我确保始终是数字。)

名称类似于:

4这是一个选项

3另一个选择

1另一

0另一个

2第二选择

我努力了:

objectArray.sort_by {|a| a.name[0].to_i}
objectArray.sort {|a,b| a.name[0].to_i <=> b.name.to_i}

在这两种情况下,我的数组排序都不会改变..(还使用了破坏性的sort!和sort_by!版本)。

我像这样遍历数组:

objectArray.each do |test|
  puts test.name[0].to_i  
  puts "\n"
end

并且肯定我看到它应该具有的整数值

尝试过这样的数组:

[
  { id: 5, name: "4rge" }, 
  { id: 7, name: "3gerg" }, 
  { id: 0, name: "0rege"}, 
  { id: 2, name: "2regerg"}, 
  { id: 8, name: "1frege"}
]

而且@ sagarpandya82的答案没有任何问题:

arr.sort_by { |a| a[:name][0] }
# => [{:id=>0, :name=>"0rege"}, {:id=>8, :name=>"1frege"}, {:id=>2, :name=>"2regerg"}, {:id=>7, :name=>"3gerg"}, {:id=>5, :name=>"4rge"}] 

只需按name排序即可。 由于字符串按字典顺序排序,因此对象将按名称的第一个字符进行排序:

class MyObject
  attr_reader :name
  def initialize(name)
    @name = name
  end

  def to_s
    "My Object : #{name}"
  end
end

names = ['4This is an option',
         '3Another option',
         '1Another one',
         '0Another one',
         '2Second option']

puts object_array = names.map { |name| MyObject.new(name) }
# My Object : 4This is an option
# My Object : 3Another option
# My Object : 1Another one
# My Object : 0Another one
# My Object : 2Second option

puts object_array.sort_by(&:name)
# My Object : 0Another one
# My Object : 1Another one
# My Object : 2Second option
# My Object : 3Another option
# My Object : 4This is an option

如果需要,还可以定义MyObject#<=>并自动获得正确的排序:

class MyObject
  def <=>(other)
    name <=> other.name
  end
end

puts object_array.sort
# My Object : 0Another one
# My Object : 1Another one
# My Object : 2Second option
# My Object : 3Another option
# My Object : 4This is an option

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM