Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 146 Vote(s) - 3.81 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Replace words in a string - Ruby

#1
I have a string in Ruby:

sentence = "My name is Robert"

How can I replace any one word in this sentence easily without using complex code or a loop?
Reply

#2
First, you don't declare the type in Ruby, so you don't need the first `string`.

To replace a word in string, you do: `sentence.gsub(/match/, "replacement")`.
Reply

#3
You can try using this way :

sentence ["Robert"] = "Roger"

Then the sentence will become :

sentence = "My name is Roger" # Robert is replaced with Roger
Reply

#4
sentence.sub! 'Robert', 'Joe'

Won't cause an exception if the replaced word isn't in the sentence (the `[]=` variant will).

## How to replace all instances?

The above replaces only the first instance of "Robert".

To replace all instances use `gsub`/`gsub!` (ie. "global substitution"):

sentence.gsub! 'Robert', 'Joe'

The above will replace all instances of Robert with Joe.
Reply

#5
If you're dealing with natural language text and need to replace a word, not just part of a string, you have to add a pinch of regular expressions to your gsub as a plain text substitution can lead to disastrous results:

'mislocated cat, vindicating'.gsub('cat', 'dog')
=> "mislodoged dog, vindidoging"

Regular expressions have word boundaries, such as `\b` which matches start or end of a word. Thus,

'mislocated cat, vindicating'.gsub(/\bcat\b/, 'dog')
=> "mislocated dog, vindicating"

In Ruby, unlike some other languages like Javascript, word boundaries are UTF-8-compatible, so you can use it for languages with non-Latin or extended Latin alphabets:

'сіль у кисіль, для весіль'.gsub(/\bсіль\b/, 'цукор')
=> "цукор у кисіль, для весіль"
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through