RubyBeginner
RubyBeginner

Reputation: 319

Replacing a word in text using Ruby

I know how to do it by using this code

poem['sleepy'] = 'busy'

What the above object type called? Is it an Array? How can I assign the poem to the first line of the text in order to replace the word "sleepy" that is sitting on that specific line?

Upvotes: 0

Views: 162

Answers (1)

rid
rid

Reputation: 63442

It's not an array, it's String's []= method. If you want to only replace on a certain line, you can split the poem string and get an array by using the split method:

lines = poem.split("\n")

You could then make the replacement on the line you wish:

lines[3]["sleepy"] = "busy"

And then you can use Array's join method to join the Array into a String again:

poem = lines.join("\n")

Upvotes: 3

Related Questions