Forum: Ruby turning off interpolation in a regex

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Jason P. (Guest)
on 2006-03-31 05:34
(Received via mailing list)
I need to be able to find a run of characters (like *count*) in a
string and substitute in the value #{object.count} so that I'm left
with a string that can itself be interpolated. The method for doing
this that jumped out was to use the string's gsub method like this:

	original_string.gsub(/\*count\*/, /count of #{object\.count}/

(Old hands at Ruby are now chuckling, and rightly so) How do I go
about getting the literal text in the substitution portion without
getting an, "NameError: undefined local variable or method `object'
for main:Object"?

Any assistance, pointers or suggestions appreciated.

--
Jason P.
removed_email_address@domain.invalid

"The computer allows you to make mistakes
faster than any other invention, with the
possible exception of handguns and tequila."
Joel VanderWerf (Guest)
on 2006-03-31 06:53
(Received via mailing list)
Jason P. wrote:
> I need to be able to find a run of characters (like *count*) in a string
> and substitute in the value #{object.count} so that I'm left with a
> string that can itself be interpolated. The method for doing this that
> jumped out was to use the string's gsub method like this:
>
>     original_string.gsub(/\*count\*/, /count of #{object\.count}/
>
> (Old hands at Ruby are now chuckling, and rightly so) How do I go about
> getting the literal text in the substitution portion without getting an,
> "NameError: undefined local variable or method `object' for main:Object"?

s = original_string.gsub(/\*count\*/, 'count of #{object.count}')

# set object somehow

eval "\"#{s}\""
Jason P. (Guest)
on 2006-03-31 07:08
(Received via mailing list)
On Mar 30, 2006, at 8:53 PM, Joel VanderWerf wrote:

> s = original_string.gsub(/\*count\*/, 'count of #{object.count}')
>
> # set object somehow
>
> eval "\"#{s}\""

Thank you, Joel.

--
Jason P.
removed_email_address@domain.invalid

"The computer allows you to make mistakes
faster than any other invention, with the
possible exception of handguns and tequila."
This topic is locked and can not be replied to.