Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/random-words/array.rb

Overview

Array helpers for RandomWords This module extends the Array class with additional methods for manipulating arrays.

Instance Method Summary collapse

Instance Method Details

#rotateObject



69
70
71
72
73
74
75
76
# File 'lib/random-words/array.rb', line 69

def rotate
  return self if empty?

  # Rotate the array by moving the first element to the end
  first_element = shift
  push(first_element)
  self
end

#split_namesArray<Array<String>, Array<String>>

Split a names list into first and last names Splits the names at blank line into two arrays: first names and last names.

Returns:



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/random-words/array.rb', line 33

def split_names
  first_names = []
  last_names = []
  full_names = []

  sections = [[]]
  idx = 0
  each do |line|
    if line.strip.empty? || line !~ /^[[:word:]]/i
      idx += 1
      sections[idx] = []
    else
      sections[idx] << line.strip
    end
  end

  if sections.length == 1
    first_names = []
    last_names = []
    full_names = sections[0]
  elsif sections.length == 2
    first_names = sections[0]
    last_names = sections[1]
    full_names = []
  else
    first_names = sections[0]
    last_names = sections[1]
    full_names = sections[2]
  end

  first_names.delete_if(&:empty?)
  last_names.delete_if(&:empty?)
  full_names.delete_if(&:empty?)
  [first_names, last_names, full_names]
end

#split_terminatorsArray<Array<String>>

Split a terminators array into terminators and extended punctuation based on a line without a comma

Returns:

  • (Array<Array<String>>)

    An array containing two arrays: the first for terminators and the second for extended punctuation



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/random-words/array.rb', line 12

def split_terminators
  terminators = []
  extended_punctuation = []
  terminators_ended = false
  each do |line|
    if line.include?(',') && !terminators_ended
      terminators << line.split(',').map(&:strip)
    elsif terminators_ended
      extended_punctuation << line.split(',').map(&:strip)
    else
      terminators_ended = true
    end
  end
  terminators.delete_if { |line| line[1].empty? }
  extended_punctuation.delete_if { |line| line[1].empty? }
  [terminators, extended_punctuation]
end