Tuesday, January 31, 2023

 def substitute(search, replace, text)

  text.gsub(search, replace)

end


text = "Hello World, this is a sample text."

search = "sample"

replace = "example"


puts substitute(search, replace, text)

# Output: "Hello World, this is a example text."

def replace_keys_with_values(hash, text)

  hash.each do |key, value|

    text.gsub!(key, value)

  end

  text

end

replace_keys_with_values({ "key1" => "value1", "key2" => "value2" }, "key1 and key2")

# returns "value1 and value2"

 

 

In this example, the substitute method uses the gsub method, which stands for "global substitution", to replace all occurrences of the search string in the text input with the replace string. The gsub method returns a new string with the replacements, and this new string is then returned by the substitute method.