josh
josh

Reputation: 75

Replacing multiple characters in Ruby string with one character

I'm trying to replace all vowels in a string with a "*"

This is what I have at the moment

string = "alphabet"

string.gsub! "a", "*"
string.gsub! "e", "*"
string.gsub! "i", "*"
string.gsub! "o", "*"
string.gsub! "u", "*"

I want string to equal "*lph*b*t". What's the easiest way to do this?

Upvotes: 1

Views: 3612

Answers (3)

Parthiv
Parthiv

Reputation: 1

In Javascript, Below is one of way to do this.

const vArr = 'aeiouy'.split('');

  const sArr = inputStr.split('');

  const binaryArray = sArr.map(i => {
    if(vArr.indexOf(i) > -1){
      return "0"; //I am trying to replace all vowels with zero
    } else {
      return i  //else replace with same char
    }
  })

  const resultStr = binaryArray.join('');

Upvotes: -1

Cary Swoveland
Cary Swoveland

Reputation: 110665

The other standard way is:

string = "alphabet"
string.gsub!(/[aeiou]/,'*')
  #=> "*lph*b*t" 
string
  #=> "*lph*b*t" 

which you could also write

string.gsub!(/[aeiou]/) {'*'}

Upvotes: 5

sawa
sawa

Reputation: 168081

The easiest I can think of is:

string.tr!("aeiou", "*")

Upvotes: 7

Related Questions