Skip to content

Instantly share code, notes, and snippets.

@adamstegman
Created August 27, 2011 01:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamstegman/1174851 to your computer and use it in GitHub Desktop.
Save adamstegman/1174851 to your computer and use it in GitHub Desktop.
Search a website for permutations of "Fillion"
#!/usr/bin/env ruby
# coding: UTF-8
require 'uri'
require 'net/http'
require 'bundler'
Bundler.require :default
# Returns all permutations of the letters in +str+.
#
# @param [String] str
# @return [Array] all permutations of the letters in +str+
def permutations str
str = str.to_s
return [str] if !str || str.size <= 1
letters = str.split(//)
perms = []
letters.each_with_index do |letter, index|
rest = str[0...index] + str[index+1..-1]
perms += permutations(rest).map {|perm| letter + perm}
end
perms.uniq
end
# Searches the text at +url+ for +regex+. Returns each matching line.
#
# @param [String] url
# @param [Regexp] regex
# @return [Array<String>] each line from +url+ matching +regex+
def search url, regex
begin
uri = URI.parse(url)
rescue URI::InvalidURIError => e
puts e.inspect
return []
end
lines = []
body = Net::HTTP.get(uri)
doc = Nokogiri::HTML(body)
doc.root.text.each_line do |line|
lines << line if line =~ regex
end
lines
end
# @return [String] the usage information for this script
def usage
%Q{#{$0} URL
#{$0} searches the response of the given URL for permutations of Fillion.
}
end
if !ARGV[0]
puts usage
exit false
end
puts search(ARGV[0], /#{permutations('fillion').join '|'}/i).join "\n"
source :rubygems
gem 'nokogiri', '~> 1.5.0'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment