Hi all. I’ve written a little script to search a csv file for films. It
works but has problems. I’d appreciate any pointers with the following:
I’ve used instance variables without a class, to make them visible
amongst methods. Is this acceptable for a short script like this?
As it is, it will only match exactly. For example, I have The Mummy
and The Mummy Returns. If I search for ‘mummy’ program reports “film not
found.” I know I need to use Regexp’s, not sure how to implement it here
though.
Any other comments gratefully received.
#################
search_films.rb
#################
require ‘csv’
def load_xvid_file(path_to_csv) @names = []
csv_contents = CSV.read(path_to_csv)
csv_contents.shift
csv_contents.each do |row| @names << row[0]
end @names.each { |f| f.downcase! }
end
def search_for_film
print "Enter name of film to search for: "
film = gets.chomp.downcase
puts
if @names.include?(film)
puts “#{film} found!”
else
puts “#{film} not found :(”
end
prompt
end
Sorry, don’t know your name. You’re just appearing as ‘guest’. Are you
sure it’s a good idea to have globals in block variables? I’ve been
continuing to play and the following seems to be what I’m after. Sadly
nothing prints out and the program exits.
def search_for_film
print "Enter name of film to search for: "
film = gets.chomp.downcase
results = @films.grep(/film/)
if results
print results
elsif results.empty?
puts “Nothing found.”
else
menu
end
end
Here is irb demonstrating that it should work!
irb(main):009:0> films = [‘the mummy’, ‘the mummy returns’, ‘the mummy
7’, ‘the daddy’]
=> [“the mummy”, “the mummy returns”, “the mummy 7”, “the daddy”]
irb(main):010:0> films.grep(/mummy/)
=> [“the mummy”, “the mummy returns”, “the mummy 7”]
irb(main):011:0>
By the way, I’d change a bit around the logic and the user interface,
you seem to have both a little bit mixed up. I would call method
prompt from the main script, in that method I would ask the user for a
word and call search_for_film passing what the user typed. From that
method I would return the results array. Back in the prompt method, I
would print the results and loop for another run. This way,
search_for_film is not tied to the specific user interaction and is
more general and easier to refactor and reuse.
Thanks Jesus. I plan to improve script over coming days.
–
Posted viahttp://www.ruby-forum.com/.
Hi Simon, just a tip, there is a ruby library to deal with CSV data in
a way very similar to ActiveRecord, but just doesn’t work with ruby
1.9. https://github.com/marcofognog/active_csv
Regards
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.