Hackerrank Ruby - Strings - Methods II Solution
1 min read

Hackerrank Ruby - Strings - Methods II Solution

Hackerrank Ruby - Strings - Methods II Solution

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 allthe 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!") # => "<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.

Solution in ruby

Approach 1.

def mask_article(str, arr)
    arr.each { |word| str.gsub!(/#{word}/, strike(word)) }

def strike(str)
    "<strike>" + "#{str}" + "</strike>"

Approach 2.

def strike(str)
    return "<strike>#{str}</strike>"
def mask_article(str, words)
    words.each{|to_rep| str.gsub!(to_rep, strike(to_rep))}
    return str

Approach 3.

# Enter your code here
def mask_article(s, words)
    words.each do |w|
        s = s.gsub(w, strike(w))
    return s

def strike(s)
    return "<strike>" + s + "</strike>"

Enjoying these posts? Subscribe for more

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.