Reputation: 87
i have this code in Ruby made to search words through any webpage.
I wonder if it's possible to improve it with Class/Methods, make it more beautiful and functional using Object Oriented. Anyone could help me, please?
require 'open-uri'
puts "Type URL you wanna search:"
url = gets.chomp
puts "Type the word you want to search:"
pattern = gets.chomp
page = open(url.to_s).read
tags = page.scan(pattern)
puts "It has #{tags.length} matches for: #{pattern} "
Upvotes: 0
Views: 59
Reputation: 211580
There's a few things you can do to improve this. The first is to encapsulate the functionality inside a descriptive class:
class PageParser
def initialize(url)
@url = url
end
def scan(word)
open(@url).read.scan(word)
end
end
I'd also strongly recommend steering towards a more command-line friendly interface. This makes running repeated tests trivial, you can usually up-arrow, run the last command over, no input necessary:
url, word = ARGV
puts PageParser.new(url).scan(word).join(', ')
You can build on that with OptionParser to make it more robust, adding flags like --verbose
and what have you.
Upvotes: 2