Question

I'm trying to figure out how to do string substitutions while in the process of porting a Perl script to Ruby.

Here's the Perl line. I'm trying to figure out Ruby's equivalent:

$historyURL =~ s/COMPONENT_NAME/$componentName/g;

For those of you who may know Ruby, but not Perl, this line basically substitutes the string "COMPONENT_NAME" in the $historyVariable with the value of the $componentName variable.

Was it helpful?

Solution

The equivalent is pretty straight-forward:

history_url.gsub!(/COMPONENT_NAME/, component_name)

The gsub! method replaces all instances of the given pattern with the second argument and stores the result in the original variable as it is an in-place modifier. gsub by comparison returns a modified copy.

OTHER TIPS

The nice thing about the gsub-method is that it does not need a regex, it works fine with a string (or a variable pointing to a string):

history_url = "some random text COMPONENT_NAME random text COMPONENT_NAME"
component_name = "lemonade"
p history_url.gsub("COMPONENT_NAME", component_name) # no regex
#=> "some random text lemonade random text lemonade"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top