Ruby - replace the first occurrence of a substring with another string
Use #sub
:
a.sub('bar', "BAR")
How to replace substring with another substring (by index from..to)
str = 'show me the money'
first = 4
last = 11
replacement = '...'
str[first..last] = replacement
str
#=> 'show...money'
Replace words in a string - Ruby
You can try using this way :
sentence ["Robert"] = "Roger"
Then the sentence will become :
sentence = "My name is Roger" # Robert is replaced with Roger
Replace substring with another string rails
Try this, assuming the string is in a variable s
:
s.gsub(/width:[^;]*;/, 'width: auto;')
Ruby match first occurrence of string for a gsub replacement
Use sub
, not gsub
. gsub
is global, sub
isn't.
How can I replace every instance of a pattern in ruby?
String.gsub should do the trick.
Quoting docs:
gsub(pattern, replacement) → new_str
Returns a copy of str with the all occurrences of pattern
substituted for the second argument. The pattern is typically a
Regexp; if given as a String, any regular expression metacharacters it
contains will be interpreted literally, e.g.\\d
will match a
backlash followed byd
, instead of a digit.
How do I remove the first occurence of a substring in string?
Use sub!
to substitute what you are trying to find with ""(nothing), thereby deleting it:
phrase.sub!("foo", "")
The !(bang) at the end makes it permanent. sub
is different then gsub
in that sub
just substitutes the first instance of the string that you are trying to find whereas gsub
finds all instances.
Java replace only first occurrence of a substring in a string
Try the replaceFirst
method. It uses a regular expression, but the literal sequence "ha"
still works.
string.replaceFirst("ha", "gurp");
Related Topics
Getting Only New Mail from an Imap Server
Rails. How to Store Time of Day (For Schedule)
Rebase Rails Migrations in a Long Running Project
Fast Way to Get Remote Image Dimensions
Edit Each Line in a File in Ruby
How to Use Xmlns Declarations with Xpath in Nokogiri
How to Test If a Div Has a Certain CSS Style in Rspec/Capybara
Regex Match Everything Up to First Period
Ruby To_JSON Issue with Error "Illegal/Malformed Utf-8"
Ruby on Rails: Devise, Want to Add Invite Code
Where in the Ruby Language Is %Q, %W, etc., Defined
Is There a "Main" Method in Ruby Like in C
How to Spawn a Child Process in Ruby
Write CSV in Ruby 1.9 and CSV::Writer