-1

I am trying to eval the expression:

eval "\"1 pages\".gsub(/\D/,'')"

It always retrieves '1 pages' while I expect only the string '1'.

Why does eval ignore gsub?

sawa
  • 165,429
  • 45
  • 277
  • 381
Samur Araújo
  • 29
  • 1
  • 4

3 Answers3

1

You need to escape the backslash since you're in an interpolated string:

eval "\"1 pages\".gsub(/\\D/, '')"

Or just don't use double-quotes since you don't need interpolation:

eval '"1 pages".gsub(/\D/, "")'
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
1

Why does eval ignore gsub?

It does not. It may look so to you because \D has no special meaning within double quotes, and hence it is interpreted as plain "D". And there is no "D" within "1 pages".

sawa
  • 165,429
  • 45
  • 277
  • 381
1

You want to escape the D as well, because that's part of the regex and not the character "D" alone:

eval "\"1 pages\".gsub(/\\D/,'')"

vikram7
  • 495
  • 3
  • 12