如何对数字字符串和单词字符串数组进行排序

时间:2014-11-05 11:50:26

标签: python ruby arrays string sorting

如何在Ruby中对Python和数组中的列表进行排序,如:

["car", "z", "9", "bus", "3"] 

让这个数组得到回报:

["bus", "car", "3", "z", "9"]

我已经开始在Ruby中构建它,因为我知道它更好。我尝试了没有参数的.sort。 然后我开始编写插入排序,希望我将它重建到我的订单并编写这个方法。

def sort
 @array.each do |value|
   index = @array.index(value)
   i = index - 1
   while i >= 0
     if value < @array[i]
       @array[i + 1] = @array[i]
       @array[i] = value
     elsif (value =~ /\d/) == 0
       # I wanted to do something here, whenever it stops at number to word comparison   but didn't come up with anything workable
     else
       break
     end
   end
 end

我所能得到的只是    [&#34; 3&#34;,&#34; 9&#34;,&#34;公交车&#34;,&#34;车&#34;,&#34; z&#34;]  但这是我必须完成的代码挑战,目标是按字母顺序和数字顺序对字符串数组进行排序,保持数字字​​符串索引与原始数组一样,只需按升序排列。我正在考虑为数字创建2个哈希,并将其键作为原始数组中的索引并仅对值进行排序,然后在新数组中以正确的顺序注入它们,但是无法编写代码它仍然不确定这是否是最好的主意。

2 个答案:

答案 0 :(得分:0)

所以这就是我如何解决它。感谢Mark Thomas提示分区和插入方法。请评论您对代码效率和清晰度的想法和建议。

def sort
  # storing indicies of number strings to map them back later
  num_indicies = @array.map {|i| @array.index(i) if (i =~ /\d/) == 0}.compact
  # if there are no numbers
  if num_indicies.empty?
    @array.sort!
    #if there are only numbers
  elsif num_indicies.length == @array.length
    @array = @array.map {|n| n.to_i}.sort
  else
    # separating numbers and words for proper sort
    separation = @array.partition {|c| (c =~ /\d/) == 0}
    # sorting first array. Converting to integer in order to sort numbers bigger than 10
    separation[0] = separation[0].map {|n| n.to_i}.sort
    # sorting array of words and letters
    separation[1].sort!
    # inserting numbers in their original spots
    index = 0
    separation[0].each do |num|
      #inserting sorted integers inside of array of sorted strings, simultaniously converting them into strings
      @array = separation[1].insert(num_indicies[index], num.to_s)
      # switching index for another iteration
      index += 1
    end
  end
end

答案 1 :(得分:-1)

您需要找到一个可以将数字转换为单词形式的宝石(或自己写一些东西)。

例如:

https://github.com/radar/humanize

其余的应该是显而易见的。