似乎无法替换字符串

时间:2015-11-19 08:49:59

标签: ruby string

我希望此字符串"THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG"具有此字符串"QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD"的空格或任何特殊字符,只要它用第二个字符串字符替换第一个字符串字符即可。我想用第一个字符串替换间隔的字符串。

3 个答案:

答案 0 :(得分:1)

这样的事情:

target = "THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG"
source = "QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD"
new_target = source.split(' ').map { |partial| target.slice!(0,partial.length) }.join(' ') 
new_target

感谢@bosskovic的评论更新了代码

答案 1 :(得分:1)

chars = "THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG".chars
"QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD".gsub(/\w/){chars.shift}

chars = "THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG"
"QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD".gsub(/\w/){chars.slice!(0)}

chars = "THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG"
"QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD".gsub(/\w/).with_index{|_, i| chars[i]}

答案 2 :(得分:0)

s = "THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG"
s2 = "QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD"
char = ' '

s2.split.each_with_index do |_count, index|
  char_location = s2.index(char)
  s.insert(char_location + index, char) if char_location
  s2.sub!(char, '')
end

=> THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG