七本目 appleにはマッチするけどgreen appleにはマッチしない置換(失敗)

str =####ここから
%Q{this green apple is an apple but is not an green apple
}###ここまで
matchword = "apple"
notmatchword = "green apple"
str.each do |line|
 word = line
 while /apple/ =~ word do
  if word.index(/#{notmatchword}/) + notmatchword.length == word.index(/#{matchword}/) + matchword.length
   print word
   word = $'
  else word =~ /apple/
   print $`
   print '***'
   word = $'
  end
 end
 if $' != nil then
  print $'
 end
end

正常に動きません!失敗でーす