Module: CompSci::Names::Pokemon
- Defined in:
- lib/compsci/names/pokemon.rb
Constant Summary collapse
- DATAFILE =
File.join(__dir__, 'pokemon.txt')
Class Method Summary collapse
- .array ⇒ Object
-
.grep(rgx, path: DATAFILE, all: false) ⇒ Object
return an array, possibly empty, if all: true return a string, possibly nil, if all: false.
- .hash ⇒ Object
-
.key(val) ⇒ Object
convert 0-25 to a lowercase alpha.
-
.read_file(path: DATAFILE) ⇒ Object
an array of all the names.
-
.read_hash(path: DATAFILE) ⇒ Object
a hash of all the names, keyed by the first letter.
-
.sample(val) ⇒ Object
return a pokemon sampled from those keyed by val.
Class Method Details
.array ⇒ Object
6 7 8 9 |
# File 'lib/compsci/names/pokemon.rb', line 6 def self.array @@array ||= self.read_file @@array end |
.grep(rgx, path: DATAFILE, all: false) ⇒ Object
return an array, possibly empty, if all: true return a string, possibly nil, if all: false
23 24 25 26 27 28 29 30 31 32 |
# File 'lib/compsci/names/pokemon.rb', line 23 def self.grep(rgx, path: DATAFILE, all: false) ary = [] File.open(path).each_line { |l| if l.match rgx ary << l.chomp break unless all end } all ? ary : ary.first end |
.hash ⇒ Object
11 12 13 14 |
# File 'lib/compsci/names/pokemon.rb', line 11 def self.hash @@hash ||= self.read_hash @@hash end |
.key(val) ⇒ Object
convert 0-25 to a lowercase alpha
44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/compsci/names/pokemon.rb', line 44 def self.key(val) if val.is_a?(String) if val.match(/^[0-9]/) val = val[0..1].to_i elsif val.match(/^[a-z]/i) return val.downcase[0] else raise(ArgumentError, "can't handle #{val}") end end CompSci::Names::ENGLISH_LOWER[val.to_i] end |
.read_file(path: DATAFILE) ⇒ Object
an array of all the names
17 18 19 |
# File 'lib/compsci/names/pokemon.rb', line 17 def self.read_file(path: DATAFILE) File.readlines(path).map { |n| n.chomp } end |
.read_hash(path: DATAFILE) ⇒ Object
a hash of all the names, keyed by the first letter
35 36 37 38 39 40 41 |
# File 'lib/compsci/names/pokemon.rb', line 35 def self.read_hash(path: DATAFILE) hsh = Hash.new { |h, k| h[k] = [] } File.open(path).each_line { |line| hsh[line.chr] << line.chomp } hsh end |
.sample(val) ⇒ Object
return a pokemon sampled from those keyed by val
58 59 60 61 |
# File 'lib/compsci/names/pokemon.rb', line 58 def self.sample(val) ary = self.hash[self.key(val)] ary.sample if ary end |