jeudi 26 février 2015

Ruby - arrays check for and replace with


Given:



check_for = ["Lorem", "ipsum", "dolor", "sit", "amet"]

replace_with = ["Donec", "ut", "libero", "sed", "arcu"]

sentence = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur."


How can I check the entire string in 'sentence' if it contains the words placed in the array 'check_for' and if they are found, replace with the words in 'replace_with'?


Words in check_for can be replaced with words in replace_with with the same index:


check_for[idx] should be replaced with replace_with[idx]


I've done something "similar" with Javascript using nested loops. For some reason this isn't working with Ruby.


My idea with nested loops was to split sentence into array and using while loops with i and j. So sentence[i] would start at 0:



sentence[i] == check_for[j]


then:



sentence[i] = replace_with[j]


Aside from this idea not working, I'm certain there is a more straight forward way in Ruby.


Case insensitive is ok.





Aucun commentaire:

Enregistrer un commentaire