Created
September 27, 2013 03:48
-
-
Save davidbella/6723850 to your computer and use it in GitHub Desktop.
Ruby: Tweet Shortener
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
replacements = { | |
"to" => '2', | |
"two" => '2', | |
"too" => '2', | |
"for" => '4', | |
"four" => '4', | |
'be' => 'b', | |
'you' => 'u', | |
"at" => "@", | |
"and" => "&" | |
} | |
tweets = [ | |
"Hey guys, can anyone teach me how to be cool? I really want to be the best at everything, you know what I mean? Tweeting is super fun you guys!!!!", | |
"OMG you guys, you won't believe how sweet my kitten is. My kitten is like super cuddly and too cute to be believed right?", | |
"I'm running out of example tweets for you guys, which is weird, because I'm a writer and this is just writing and I tweet all day. For real, you guys. For real.", | |
"GUISEEEEE this is so fun! I'm tweeting for you guys and this tweet is SOOOO long it's gonna be way more than you would think twitter can handle, so shorten it up you know what I mean? I just can never tell how long to keep typing!" | |
] | |
def shorten_tweet(tweet, replacements) | |
if tweet.length <= 140 | |
return tweet | |
end | |
new_tweet = [] | |
tweet.split().each do |word| | |
# has_key? is the ruby way - stop thinking in perl | |
new_tweet << (replacements[word.downcase] ? replacements[word.downcase] : word) | |
end | |
new_tweet.join(' ')[0, 140] | |
end | |
# Still doesn't work as far as uppercase letters but just stop for now | |
def shorten_tweet2(tweet, replacements) | |
if tweet.length <= 140 | |
return tweet | |
end | |
replacements.keys.each do |key| | |
mod_key = key.downcase.center(key.length + 2) | |
tweet.gsub! mod_key, ' ' + replacements[key] + ' ' | |
end | |
tweet[0, 140] | |
end | |
tweets.each do |tweet| | |
puts shorten_tweet(tweet, replacements) | |
puts shorten_tweet2(tweet, replacements) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment