1

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
    words.push(word)
end

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

puts words

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

1
  • @tadman gave a good answer, but in future consider waiting longer before selecting an answer. Quick selections can discourage other answers and short-circuit those still working on answers. There's no rush. Many here wait at least a couple of hours before making a selection, some wait much longer. Commented Oct 15, 2016 at 6:07

1 Answer 1

2

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')
end

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Any reason for gsub(/s/, 'th') rather than gsub('s', 'th')?
@CarySwoveland Better to learn about Regular Expressions early than be confused and scared about them forever, that's all. Trial by fire!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.