Ruby - replace characters in a string with a symbol

Viewed 5140

I am trying to receive a string of characters and change all characters aside from spaces to "*". Here is where I am:

def change_word(word)
  new_word.each {|replace| replace.gsub!(/./, "*") }
  new_word.to_s
  new_word.join
end

I'm taking a word, adding the individual characters to an array and assigning this to a new variable, replacing everything in said array with the required symbol, changing everything in the array to a string and then joining everything in the array to output a bunch of *'s.

What I would like to do (and it's not necessary that the solution follows the previous syntax) is take all letters and replace them with *. Spaces should stay as a space, only letters should become *.

2 Answers

What about gsub(/\S/, '*')

It will find all non-whitespace characters and replace every one of them with *. \S is a regex character class matching non-whitespace chars (thanks @jdno).

E.g.

 pry> "as12 43-".gsub(/\S/, '*')
 => "**** ***"

So in your case:

def change_word(word)
   word.gsub(/\S/, '*')
end 

You may also extract the regex outside of the method to optimize it a bit:

CHANGE_WORD_PATTERN = /\S/
def change_word(word)
   word.gsub(CHANGE_WORD_PATTERN, '*')
end 

When the first argument from the tr method of String starts with "^", then it means: everything but. So "^ " means everything but a space.

word = "12 34 rfv"
word.tr("^ ","*")  # => "** ** ***" 
Related