In this HackerRank Ruby – Strings – Methods II problem solution In this challenge, your task is to write the following methods:
mask_article which appends strike tags around certain words in a text. The method takes 2 arguments: A string and an array of words. It then replaces all the instances of words in the text with the modified version.
A helper method strike, given one string, appends strike-off HTML tags around it. The strike-off HTML tag is <strike></strike>.
For example:
> strike(“Meow!”) # => “<strike>Meow!</strike>”
> strike(“Foolan Barik”) # => “<strike>Foolan Barik</strike>”
> mask_article(“Hello World! This is crap!”, [“crap”])
“Hello World! This is <strike>crap</strike>!”
Apply the helper method in completing your main method.
Problem solution.
# Enter your code here def strike word "<strike>#{word}</strike>" end def mask_article s, arr arr.each do | w | striked = strike w s = s.gsub( /#{Regexp.escape( w )}/, striked ) end return s end
Second solution.
def strike (s) "<strike>" + s + "</strike>" end def mask_article (str, arr) arr.each do |word| str.gsub!(word, strike(word)) end str end
Third solution.
# Enter your code here def mask_article(article, strike_words) strike_words.reduce(article) { |article, word| article.gsub(word, strike(word)) } end def strike(string) "<strike>#{string}</strike>" end