Class: Runglish::Converter

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

Direct Known Subclasses

LatToRusConverter, RusToLatConverter

Instance Method Summary collapse

Constructor Details

#initialize(lower_single, lower_multi, upper_single, upper_multi) ⇒ Converter

Returns a new instance of Converter.



12
13
14
15
16
17
18
19
20
21
# File 'lib/runglish.rb', line 12

def initialize(lower_single, lower_multi, upper_single, upper_multi)
  @lower_single = lower_single
  @lower_multi = lower_multi
  @upper_single = upper_single
  @upper_multi = upper_multi

  @lower = (@lower_single.merge(@lower_multi)).freeze
  @upper = (@upper_single.merge(@upper_multi)).freeze
  @multi_keys = (@lower_multi.merge(@upper_multi)).keys.sort_by {|s| s.length}.reverse.freeze
end

Instance Method Details

#transliterate(str) ⇒ Object

Transliterate a string



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/runglish.rb', line 24

def transliterate(str)
  chars = str.scan(%r{#{@multi_keys.join '|'}|\w|.})

  result = ""

  chars.each_with_index do |char, index|
    if @upper.has_key?(char) && @lower.has_key?(chars[index+1]) # combined case
      result << @upper[char].downcase.capitalize
    elsif @upper.has_key?(char)
      result << @upper[char]
    elsif @lower.has_key?(char)
      result << @lower[char]
    else
      result << char
    end
  end

  result
end