I am trying to solve this problem: given a string, you are asked to sort it according to characters order in other string:
Example:
> sort_string('foos', 'of')
=> 'oofs'
> sort_string('string', 'gnirts')
=> 'gnirts'
> sort_string('banana', 'abn')
=> 'aaabnn'
I've tried following implementation:
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
But it gives me following error:
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 `'
sort_string('zaefc', 'fa')to returnefcaz? Here'f'and 'a' are at offsets3and1of'zaefc'. Are those two letters to be swapped, but retain positions1and3, and are the remaining characters,'z','e'and'c', to be ordered lexiographically but remain at offsets0,2and4?