ruby - two-way search with Hashes? -
ruby - two-way search with Hashes? -
i'm trying create database search programme using hash db storage.
i can search list using fellow member numbers how search using fragments of numbers (so entering 1
give 001
, 010
, 011
, 021
, etc...) or fragmented/full usernames (entering ni
give nightc||ed
, oni
)
my current code follows:
#rdb nightc||ed, ©2015 db = hash.new() db["001"] = "oni" db["002"] = "eclipse" db["003"] = "saikou" db["004"] = "nightc||ed" db["005"] = "anime" db["006"] = "master" x = 0 num = db.count puts "in: member:" num.times |pair| puts "#{db.keys[x]} | #{db.values[x]}" x += 1 end puts "------------------- come in index number:" = gets.to_i -= 1 scheme "cls" puts "in: member: #{db.keys[i]} | #{db.values[i]}" sleep
first, iterate on hash. within each iteration, utilize include?
search partial results in key and/or value.
here's way allow user come in either partial number or partial name:
db = hash.new() db["001"] = "oni" db["002"] = "eclipse" db["003"] = "saikou" db["004"] = "nightc||ed" db["005"] = "anime" db["006"] = "master" puts "enter search term" search_term = gets.chomp.downcase results = db.select |k,v| k.downcase.include?(search_term) || v.downcase.include?(search_term) end results.size.times |x| puts "#{results.keys[x]} | #{results.values[x]}" end
results:
enter search term 1 001 | oni come in search term ni 001 | oni 004 | nightc||ed 005 | anime
ruby hash
Comments
Post a Comment