ActiveSupport::Inflector::Inflections#human uses a \1 in the example:

human /_cnt$/i, '\1_count'

As far as I can tell, that's actually adding a \u0001 character to the string, and it seems to still work if I just use '_count'. Can anyone tell me what the \1 is actually supposed to be doing?

有帮助吗?

解决方案

It may be that under the hood, they are passing that string to gsub or something similar. In a gsub replacement string, '\1' has a special meaning -- it refers to whatever the first capturing group in the regex argument matched.

For example, try:

 "a short sentence".gsub(/([aeiou])/, '\1\1')

If you use "\1", now that is a completely different thing. That is a \u001 character. (Escapes work differently in single-quoted and double-quoted Ruby strings.)

Probably the reason why omitting the \1 doesn't seem to change anything in the example you gave, is because there is no capturing group in the regex.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top