Mystic Chimp
Mystic Chimp

Reputation: 115

Read from array1 write from array2

Just learning some basic Ruby concepts as a beginner. Not really looking for code as such, rather some fundamental principles behind the following question (obviously feel free to express yourself with code if you need to :0)

In a simple redact text exercise, a user enters some text, then enters the word to be redacted, I'm fine with this and can make it work a number of ways. However...

to deal with the possibility the user could enter upper and/or lower case letters for either the text or redacted word, I would need to create variables .downcase! again no problem there. But what if once the program runs, you want to return the words to their original state?

I thought perhaps you would need to create an array for the original text, where each word has an index within the array, create a corresponding array with the lowercase letters and if a word is NOT redacted, then you would compare the index from the lowercase array and write the corresponding index from the original array... does this sound correct or am I over thinking it, is there an easier way?

Thanks for your help

puts " What is your message"
text1 = gets.chomp
text2 = text1.downcase
puts "What is your secret word"
redact = gets.chomp.downcase!
words = text2.split (" ")
words.each do |x|
  if 
   x == redact
   print "REDACTED" + " "
 else
   print x + " "
   end
end

I've added my working code, you can see that I've separated text1 the original from text2 which isn't strictly necessary as it stands, but to maintain the original formatting

Upvotes: 1

Views: 59

Answers (1)

Justin Hellreich
Justin Hellreich

Reputation: 575

Your solution sounds like it could work and as a beginner it may be useful to write a complete solution like that. But don't forget that ruby can do a lot of fun stuff for you.

Lets say we take input into sentence and the string to redact is stored in redact.

We can do something as simple as this:

sentence.gsub(/#{redact}/i, "*" * redact.length)

gsub finds all occurrences of the first argument and replaces it with the second, returning a new string. First notice that we are using the redacted string as a regular expression for the first arg and the i indicates that it should match case insensitive, as you wanted. Now the second arg is simply a string of asterisks of equivalent length to the redacted string.

For example if we have the following:

sentence = 'this is My Sentence'
redact = 'my'
puts sentence.gsub(/#{redact}/i, "*" * redact.length)

The above method will print this is ** Sentence.

Just one extra thing to note: this regex will match all occurrences of the string. For example, if redact = 'is', the resulting sentence will be th** ** My Sentence. You can re-write the regex to avoid this if that's not the expected use case.

Upvotes: 3

Related Questions