HackerRank Ruby Strings Methods II Solution

Hello coders, In this post, you will learn how to solve HackerRank Ruby Strings Methods II Solution. This problem is a part of the Ruby Tutorial series. One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions.

HackerRank Ruby Strings Methods II Solution
HackerRank Ruby Strings Methods II Solution

HackerRank Ruby Strings Methods II Solution

Let’s get started with Ruby Strings Methods II Solution

Problem Statement

In this tutorial, we’ll learn about the methods in String class that help us to search and replace portions of the string based on a text or pattern.

  • String.include?(string) – Returns true if str contains the given string or character. Very simple!
    > "hello".include? "lo"   #=> true  
    > "hello".include? "ol"   #=> false  
  • String.gsub(pattern, <hash|replacement>) – Returns a new string with all the occurrences of the pattern substituted for the second argument: . The pattern is typically a Regexp, but a string can also be used.
    "hello".gsub(/[aeiou]/, '*')                  #=> "h*ll*"
    "hello".gsub(/([aeiou])/, '')             #=> "hll"

Either method will depend upon the problem you are trying to solve, and the nature of input-output behavior you desire.

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!”) # => “Meow!”
strike(“Foolan Barik”) # => “Foolan Barik”
mask_article(“Hello World! This is crap!”, [“crap”])
“Hello World! This is crap!”

Apply the helper method in completing your main method.

HackerRank Ruby Strings Methods II Solution

def mask_article(text, words_array)
  words_array.each { |word| text.gsub!(word, strike(word)) }
  return text
end
def strike s
  "<strike>#{s}</strike>"
end

Note: This problem (Ruby – Strings – Methods II  is generated by HackerRank but the solution is provided by Chase2Learn. This tutorial is only for Educational and Learning purpose.

Sharing Is Caring