سؤال

I'm solving http://www.rubeque.com/problems/a-man-comma--a-plan-comma--a-canal--panama-excl-/solutions but I'm a bit confused about treating #{} as comment in regexp. My code look like this now

def longest_palindrome(txt)
  txt[/#{txt.reverse}/]
end

I tried txt[/"#{txt.reverse}"/] or txt[#{txt.reverse}] but nothing works as I wish. How should I implicate variable into regexp?

هل كانت مفيدة؟

المحلول

This is not something you can do with a regex.

While you could use variable interpolation in the construction of a regex (see the other answers/comments), that wouldn't help you here. You could only use that to reverse a literal string, not a regex match result. Even if you could, you still wouldn't have solved the "find the longest palindrome" part, at least not with acceptable runtime performance.

Use a different approach to the problem.

نصائح أخرى

It is hard to tell how do you wish that happens without examples, but I suppose you are after

txt[/#{Regexp.escape(txt.reverse)}/]

See the Regexp#escape method

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top