我正在尝试解决这个问题:给定一个字符串,要求您根据其他字符串中的字符顺序对其进行排序:
例子:
> sort_string('foos', 'of')
=> 'oofs'
> sort_string('string', 'gnirts')
=> 'gnirts'
> sort_string('banana', 'abn')
=> 'aaabnn'
我尝试了以下实现:
def sort_string(f_string, s_string)
sanitize(s_string)
s_string.chars.each do |e|
f_string.length.times do |n|
if f_string[n] == e
s_string[e], s_string[n] = s_string[n], s_string[e]
end
end
end
end
private
def sanitize(string)
string.chars.uniq.join
end
但它给了我以下错误:
4_AStringOfSorts.rb:6:in `[]=': no implicit conversion of nil into String (TypeError) from 4_AStringOfSorts.rb:6:in `block (2 levels) in sort_string' from 4_AStringOfSorts.rb:4:in `times' from 4_AStringOfSorts.rb:4:in `block in sort_string' from 4_AStringOfSorts.rb:3:in `each' from 4_AStringOfSorts.rb:3:in `sort_string' from 4_AStringOfSorts.rb:18:in `'
最佳答案
注意事项:
您的方法在 Ruby 中不是惯用的(即使按照命令式标准,它也过于复杂)
sanitize(s_string)
:您没有捕获此方法的结果,因此它什么都不做。
一种更惯用和更实用的方法:
def sort_string(s, order)
s.chars.sort_by { |c| order.index(c) || order.size }.join
end
关于ruby - 如何根据给定的字符顺序对字符串进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28569169/