Class: GengoSearch::Gengo

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

Constant Summary collapse

ERAS =
CSV.read(File.expand_path('../data/era_names.csv', __FILE__))

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ad_year = nil) ⇒ Gengo

Returns a new instance of Gengo.



10
11
12
13
14
15
16
17
# File 'lib/gengo_search.rb', line 10

def initialize(ad_year = nil)
  if ad_year.nil? || !(ad_year.is_a?(Integer)) || ad_year < 645 || ad_year > 9999 then
    raise ArgumentError, "Please set a correct number(645~9999)"
  else
    started_year_index = search(ad_year)
    setTargetEra(started_year_index, ad_year)
  end
end

Instance Attribute Details

#hiraganaObject (readonly)

Returns the value of attribute hiragana.



6
7
8
# File 'lib/gengo_search.rb', line 6

def hiragana
  @hiragana
end

#kanjiObject (readonly)

Returns the value of attribute kanji.



6
7
8
# File 'lib/gengo_search.rb', line 6

def kanji
  @kanji
end

#romajiObject (readonly)

Returns the value of attribute romaji.



6
7
8
# File 'lib/gengo_search.rb', line 6

def romaji
  @romaji
end

#yearObject (readonly)

Returns the value of attribute year.



6
7
8
# File 'lib/gengo_search.rb', line 6

def year
  @year
end

Instance Method Details

#search(target = 0) ⇒ Object

Using Binary Search



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

def search(target = 0)

  head = 0
  tail = ERAS.count - 1

  if ERAS[tail][0].to_i <= target then
    return tail
  else
    while head <= tail

      center = (head + tail) / 2
  
      if ERAS[center][0].to_i <= target && target < ERAS[center + 1][0].to_i then
        return center
      elsif ERAS[center][0].to_i < target
        head = center + 1
      else
        tail = center - 1
      end
    end
  end


end

#setTargetEra(started_year_index = 0, ad_year = 0) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/gengo_search.rb', line 45

def setTargetEra(started_year_index = 0, ad_year = 0)
  year = ad_year - ERAS[started_year_index][0].to_i + 1
  if year == 1 then
    @kanji = "#{ERAS[started_year_index][1]} 元年"
    @hiragana = "#{ERAS[started_year_index][3]} がんねん"
    @romaji = "#{ERAS[started_year_index][2]} GANNEN"
  else
    @kanji = "#{ERAS[started_year_index][1]} #{year}"
    @romaji = "#{ERAS[started_year_index][2]} #{year}NEN"
    @hiragana = "#{ERAS[started_year_index][3]} #{year}ねん"
  end
end