Class: Lexoranking::Main

Inherits:
Object
  • Object
show all
Defined in:
lib/lexoranking/main.rb

Overview

Main class that calculates the ranking value based on some previous and next elements.

Defined Under Namespace

Classes: InvalidRankError

Constant Summary collapse

MIN_CHAR =
"a"
MAX_CHAR =
"z"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(prev, after) ⇒ Main

Returns a new instance of Main.



18
19
20
21
# File 'lib/lexoranking/main.rb', line 18

def initialize(prev, after)
  @prev = prev || MIN_CHAR
  @after = after || MAX_CHAR
end

Instance Attribute Details

#afterObject

Returns the value of attribute after.



60
61
62
# File 'lib/lexoranking/main.rb', line 60

def after
  @after
end

#prevObject

Returns the value of attribute prev.



60
61
62
# File 'lib/lexoranking/main.rb', line 60

def prev
  @prev
end

Class Method Details

.perform(prev, after) ⇒ Object



13
14
15
# File 'lib/lexoranking/main.rb', line 13

def perform(prev, after)
  new(prev, after).calculate_ranking
end

Instance Method Details

#calculate_rankingObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/lexoranking/main.rb', line 23

def calculate_ranking
  rank = ""
  i = 0

  loop do
    prev_char = get_char(prev, i, MIN_CHAR)
    after_char = get_char(after, i, MAX_CHAR)

    if prev_char == after_char
      rank += prev_char
      i += 1
      next
    end

    mid_char = mid(prev_char, after_char)
    if mid_char == prev_char || mid_char == after_char
      rank += prev_char
      i += 1
      next
    end

    rank += mid_char
    break
  end

  rank
end

#get_char(str, idx, default_char) ⇒ Object



56
57
58
# File 'lib/lexoranking/main.rb', line 56

def get_char(str, idx, default_char)
  idx >= str.length ? default_char : str[idx]
end

#mid(prev, after) ⇒ Object



51
52
53
54
# File 'lib/lexoranking/main.rb', line 51

def mid(prev, after)
  middle_ascii = ((prev.ord + after.ord) / 2).round
  middle_ascii.chr
end