Felice Mistream Felice Mistream - 4 months ago 17
Ruby Question

Modify a string using a loop in Ruby

I have an array with strings. I need to check if strings contain the letter "s". If yes, I have to replace it with "th".

Basically, that's all.

n = gets.to_i
word = ""
words = Array.new(n)
for i in 1..n
word = gets

for w in 1..words.size
for i in 0..word.length
if w[i] == "s"
w[i] = "th"

puts words

It replaces nothing (just returns the input) and I don't know why.


It looks like you're just getting started in Ruby, so here's some tips. The most obvious thing that's out of sorts here is the use of for, which, strange as it might sound, is almost never used in Ruby. The each enumerator and friends are used almost exclusively for the purpose of iterating over things, and they're better because they do a lot more than simply iterate. each_with_index and each_with_object are essential.

You're also using a lot of intermediate variables that don't really serve any function, the code would be a lot neater with collapsing it together.

For example, to get a list of words from the standard input:

words = $stdin.readlines.map(&:chomp)

That takes in all the lines of input and runs chomp on each one, removing any newline characters.

If you want to re-write this list to replace s with th then do this:

words.map! do |word|
  word.gsub(/s/, 'th')

The gsub method normally replaces a regular expression match with a string. In this case it's matching versus a letter s. These can get way more complicated, and I strongly encourage you to have a look at them and at least get a sense of what they can do. It's a tricky, yet subtly powerful tool that will come in handy all the time.

Remember Ruby has unusually specific documentation. If you have an object of type String, all the methods String can do are spelled out in the API documentation. Don't be shy about checking that, there's a ton of very useful tools in there.