如何在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个哈希,并将其键作为原始数组中的索引并仅对值进行排序,然后在新数组中以正确的顺序注入它们,但是无法编写代码它仍然不确定这是否是最好的主意。
答案 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)