2

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.

ikegami
  • 367,544
  • 15
  • 269
  • 518
dsw88
  • 4,400
  • 8
  • 37
  • 50
  • I'm curious why this question was downvoted, it seems like a perfectly legitimate question to me, one that I wasn't able to resolve by myself looking at Ruby's API (due to my lack of experience with regular expressions in general) – dsw88 Feb 25 '13 at 16:02

2 Answers2

5

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.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • The `=~` operator exists in Ruby but cannot be used to make modifications as in Perl. It's generally not used, though, in favor of using `match` or the various `sub` methods for reasons of clarity. – tadman Feb 25 '13 at 16:21
0

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"
steenslag
  • 79,051
  • 16
  • 138
  • 171