Module: CompSci::Names::Pokemon

Defined in:
lib/compsci/names/pokemon.rb

Constant Summary collapse

DATAFILE =
File.join(__dir__, 'pokemon.txt')

Class Method Summary collapse

Class Method Details

.arrayObject



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

.hashObject



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 { |l|
    hsh[l[0]] << l.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