Search code examples
ruby-on-rails-4slicemeta-tags

Using slice to remove "The" from meta tag description


I have a meta tag description where I want to get the grant name. However many of the grant names start with The like "The Smithsonian Grant". I want my meta tag to say "Apply online to the Smithsonian Grant" not "the The Smithsonian Grant". How would I go about removing the first word of the grant name if it is "The"?

I tried this:

<% meta_description "Apply online to the #{@grant.name.slice("The")} on Instrumentl" %>

but the result is

<meta name="description" content="Apply online to the The on Instrumentl" />

That wasn't how I was expecting slice to work. I also tried .slice!, .reduce, and .except in place of .slice but none of those worked. Any ideas?


Solution

  • I would use gsub which will replace any part of a matched string with replacement string. If the replacement string is empty, it'll just remove the matched string entirely:

    >> "The Smithsonian Grant".gsub(/^the */i, "")
    => "Smithsonian Grant"
    
    >> "Winnie the pooh".gsub(/^the */i, "")
    => "Winnie the pooh"