Ruby 按字符串的第一个字符对包含对象的数组进行排序

Ruby sort array with objects by first character of string

这是我第一次尝试使用 ruby,这可能是一个简单的问题,我已经卡了一个小时了,我有一个 ruby 数组,里面有一些对象,我希望该数组按对象名称 属性 中的第一个字符排序(我确保它始终是一个数字。)

名称类似于:

4This is an option

3Another option

1Another one

0Another one

2Second option

我试过:

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

在这两种情况下,我的数组排序都没有改变..(还使用了排序的破坏性版本!和 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 排序。由于字符串按 lexicographic 顺序排序,因此对象将按名称的第一个字符排序:

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