Skip to content

Instantly share code, notes, and snippets.

@lrechert
Last active April 18, 2016 18:41
Show Gist options
  • Select an option

  • Save lrechert/dac861cff58525a59c2248c84420bf4e to your computer and use it in GitHub Desktop.

Select an option

Save lrechert/dac861cff58525a59c2248c84420bf4e to your computer and use it in GitHub Desktop.
Ruby Weekly Challenge - hashtags
# Description:
#
# You start working for a fancy new startup hoping to revolutionize social networking! GASP! They had this great idea that users should be able to specify relevant keywords to their posts using an ingenious idea by prefixing those keywords with the pound sign (#). Your job is to extract those keywords so that they can be used later on for whatever purposes.
#
# Note:
# Pound signs alone do not count, for example: the string "#" would return an empty array.
# If a word is preceded by more than one hashtag, only the last hashtag counts (e.g. "##alot" would return ["alot"])
# Hashtags cannot be within the middle of a word (e.g. "in#line hashtag" returns an empty array)
# Hashtags must precede alphabetical characters (e.g. "#120398" or "#?" are invalid)
#
# Input: String of words, where some words may contain a hashtag.
#
# Output: Array of strings that were prefixed with the hashtag, but do not contain the hashtag.
def extract_hashtags(tweet)
return [] unless tweet
tweet.downcase.scan(/\B#+([a-z]*)/i).flatten.reject(&:empty?)
end
require_relative '../extract_hashtags'
describe "#extract_hashtags" do
context "when tweet is nil" do
it "returns an empty array" do
expect(extract_hashtags nil).to eql []
end
end
context "when tweet contains valid hashtags" do
it "returns only valid hashtags" do
expect(extract_hashtags("#ermigawd #ilovehashtags, like so much!")).to eql %w[ermigawd ilovehashtags]
end
end
context "when tweet contains invalid hashtags" do
it "returns only valid hashtags" do
expect(extract_hashtags("#Ermigawd #ilovehashtags, like so much! #123invalidhashtags make me #Sadlaurie. ####validhashtags makes me #happylaurie")).to eql %w[ermigawd ilovehashtags sadlaurie validhashtags happylaurie]
end
it "returns an empty array" do
expect(extract_hashtags("in#line hashtag")).to eql []
end
it "returns an empty array" do
expect(extract_hashtags "#120398" ).to eql []
end
it "returns an empty array" do
expect(extract_hashtags "#?" ).to eql []
end
it "returns an empty array" do
expect(extract_hashtags "#" ).to eql []
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment