Class: KeyboardDistance

Inherits:
Object
  • Object
show all
Defined in:
lib/keyboard_distance.rb,
lib/keyboard_distance/version.rb

Constant Summary collapse

SHIFT_DISTANCE =
1.0
ALT_DISTANCE =
0.5
SPACE_DISTANCE =
2.0
UNKNOWN_CHAR_DISTANCE =
3.0
VERSION =
"0.0.1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ KeyboardDistance



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/keyboard_distance.rb', line 15

def initialize(options={})
  @layout = options[:layout] || :qwerty
  raise "Unknown layout :#{@layout}" unless KeyboardLayout.layout_defined?(@layout)

  @national_keys = options[:national_keys] || :polish 
  raise "Unknown national keys #{@national_keys}" unless !@national_keys ||
    KeyboardLayout.national_defined?(@national_keys)

  @shift_distance = options[:shift_distance] || SHIFT_DISTANCE
  @alt_distance = options[:alt_distance] || ALT_DISTANCE
  @space_distance = options[:space_distance] || SPACE_DISTANCE
  @unknown_char_distance = options[:unknown_char_distance] || UNKNOWN_CHAR_DISTANCE

  @distances = calculate_distances
  @max_distance = calculate_max_distance

  @shift_map = KeyboardLayout.build_shifted_keys_map(@layout)
  @alt_map = KeyboardLayout.build_alted_keys_map(@national_keys) if @national_keys
end

Instance Attribute Details

#max_distanceObject (readonly)

Returns the value of attribute max_distance.



8
9
10
# File 'lib/keyboard_distance.rb', line 8

def max_distance
  @max_distance
end

Instance Method Details

#character_distance(char_1, char_2) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/keyboard_distance.rb', line 54

def character_distance(char_1, char_2)
  return 0.0 if char_1 == char_2
  return @space_distance if char_1 == ' ' || char_2 == ' '
  dist = 0.0

  if @national_keys
    key_1, key_2, difference = unalt_keys(char_1, char_2)
    dist += @alt_distance if difference
  end

  key_1, key_2, difference = unshift_keys(key_1 || char_1, key_2 || char_2)
  dist += @shift_distance if difference

  return dist if key_1 == key_2

  dist + (@distances[keys_signature(key_1, key_2)] || @unknown_char_distance)
end

#distance(word_1, word_2) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
# File 'lib/keyboard_distance.rb', line 42

def distance(word_1, word_2)
  return nil unless word_1.size == word_2.size
  return 0.0 if word_1 == word_2

  dist = 0.0
  word_1.each_char.with_index do |char_1, idx|
    dist += character_distance(char_1, word_2[idx])
  end

  dist
end

#similarity(word_1, word_2) ⇒ Object



35
36
37
38
39
40
# File 'lib/keyboard_distance.rb', line 35

def similarity(word_1, word_2)
  return nil unless word_1.size == word_2.size

  max_word_length = [word_1.size, word_2.size].max
  1.0 - distance(word_1, word_2) / (max_word_length * @max_distance)
end