num2words 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: ed408cbe7ab8e51dc7ee381eb516bd72a621e9edea1519a4237e2623a3560cf3
4
+ data.tar.gz: d9ab27fd319195b92f467d12d6722becd09791669a1639441a959e2a7a370cb0
5
+ SHA512:
6
+ metadata.gz: 4b96c5fa0203e812683760edb0c1ae6f4f6c84966ba831b14f0f79913f8b560bf478d201765b13da0bbe59ba1ad307f3bb7b9f9e7b7041b997e8ccdee03f18b5
7
+ data.tar.gz: 9b35076edef208aec9d066dbfa6abf8c42842df9c7616f9396c6baa78aa3c78abd1b5d47da5b9ba630ad27e96a19339b935465ba1579b6e89f2f32cc4a004014
data/.gitignore ADDED
@@ -0,0 +1,18 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # IDE specific files (e.g., RubyMine, IntelliJ IDEA)
11
+ .idea/
12
+
13
+ # Operating system specific files
14
+ .DS_Store
15
+
16
+ # Ignore Gemfile.lock in libraries (gems)
17
+ # In applications, Gemfile.lock should generally be committed.
18
+ Gemfile.lock
data/Gemfile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in num2words.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 12.0"
9
+
10
+ group :development, :test do
11
+ gem "rspec", "~> 3.12"
12
+ end
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Ruslan Fedotov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,136 @@
1
+ # num2words
2
+
3
+ 📦 **num2words** — Ruby-гем для преобразования чисел в строковое представление (прописью).
4
+
5
+ ✨ Основные фичи:
6
+ - 🇷🇺 Поддержка русского языка (включая склонения)
7
+ - 💰 Работа с валютами (рубли и копейки)
8
+ - 🔠 Склонения в зависимости от числа (1 рубль, 2 рубля, 5 рублей)
9
+ - 📏 Поддержка чисел до **триллиона**
10
+ - ⚙️ Опция выбора рода (один/одна, два/две)
11
+ - 🚀 Готово для интеграции в Rails
12
+
13
+ ---
14
+
15
+ ## 🚀 Установка
16
+
17
+ В Gemfile:
18
+
19
+ ```ruby
20
+ gem "num2words"
21
+ ```
22
+
23
+ или напрямую:
24
+
25
+ ```bash
26
+ gem install num2words
27
+ ```
28
+
29
+ ---
30
+
31
+ ## 💡 Использование
32
+
33
+ ```ruby
34
+ require "num2words"
35
+
36
+ Num2words.to_words(21)
37
+ # => "двадцать один"
38
+
39
+ Num2words.to_currency(21.01)
40
+ # => "двадцать один рубль одна копейка"
41
+
42
+ Num2words.to_currency(105.15)
43
+ # => "сто пять рублей пятнадцать копеек"
44
+ ```
45
+
46
+ ---
47
+
48
+ ## 🔢 Расширение числовых классов
49
+
50
+ Gem добавляет метод `to_words` для объектов `Integer` и `Float`.
51
+ Это позволяет удобно переводить числа в текст прямо на самих числах:
52
+
53
+ ```ruby
54
+ 123.to_words
55
+ # => "сто двадцать три"
56
+
57
+ 22.to_words(feminine: true)
58
+ # => "сто двадцать две"
59
+
60
+ 21.01.to_currency
61
+ # => "двадцать один рубль одна копейка"
62
+ ```
63
+
64
+ ---
65
+
66
+ ## ⚙️ Опции
67
+
68
+ ### Род числительных
69
+ ```ruby
70
+ Num2words.to_words(1)
71
+ # => "один"
72
+
73
+ Num2words.to_words(1, feminine: true)
74
+ # => "одна"
75
+ ```
76
+
77
+ ### Поддержка больших чисел
78
+ ```ruby
79
+ Num2words.to_words(1_000_000)
80
+ # => "один миллион"
81
+
82
+ Num2words.to_words(2_345_678_901)
83
+ # => "два миллиарда триста сорок пять миллионов шестьсот семьдесят восемь тысяч девятьсот один"
84
+ ```
85
+
86
+ ---
87
+
88
+ ## 🧪 Тесты
89
+
90
+ ```bash
91
+ bundle exec rspec
92
+ ```
93
+
94
+ ## 📌 Roadmap
95
+
96
+ - [ ] 🇬🇧 Поддержка английского языка
97
+ - [ ] 💵 Поддержка других валют (USD, EUR)
98
+ - [ ] 🔠 Опция выбора регистра (строчные/Прописные)
99
+
100
+ ---
101
+
102
+ ## Консоль 💻
103
+
104
+ Num2words поддерживает интерактивную консоль для быстрого тестирования.
105
+ Это удобно при работе с разными числами и языками.
106
+
107
+ ### Запуск консоли
108
+
109
+ ```bash
110
+ bin/console
111
+ ```
112
+
113
+ После запуска появится приветственное сообщение:
114
+
115
+ ```bash
116
+ 🔢 Добро пожаловать в консоль num2words!
117
+ Попробуйте: Num2words.to_words(2025)
118
+ -----------------------------------------------------
119
+ ```
120
+
121
+ 👉 Это позволяет проверять работу гема без написания отдельных скриптов.
122
+
123
+ ## 🤝 Вклад
124
+
125
+ Pull request’ы приветствуются!
126
+
127
+ 1. Сделайте fork
128
+ 2. Создайте ветку `git checkout -b feature/my-feature`
129
+ 3. Commit: `git commit -m 'Добавил мою фичу'`
130
+ 4. PR 🚀
131
+
132
+ ---
133
+
134
+ ## 📜 Лицензия
135
+
136
+ [MIT](LICENSE)
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ # таска для запуска тестов
7
+ RSpec::Core::RakeTask.new(:spec)
8
+
9
+ # по умолчанию запускаем тесты
10
+ task default: :spec
data/bin/console ADDED
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "num2words"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ # Красивое приветствие
15
+ puts "🔢 Добро пожаловать в консоль num2words!"
16
+ puts "Можете использовать: Num2words.to_words(#{Time.now.year})"
17
+ puts "-------------------------------------------------------------"
18
+
19
+ require "irb"
20
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Num2words
4
+ class Converter
5
+ ONES_MASC = %w[ноль один два три четыре пять шесть семь восемь девять].freeze
6
+ ONES_FEM = %w[ноль одна две три четыре пять шесть семь восемь девять].freeze
7
+
8
+ TEENS = %w[десять одиннадцать двенадцать тринадцать четырнадцать пятнадцать
9
+ шестнадцать семнадцать восемнадцать девятнадцать].freeze
10
+
11
+ TENS = [nil, nil, "двадцать", "тридцать", "сорок", "пятьдесят",
12
+ "шестьдесят", "семьдесят", "восемьдесят", "девяносто"].freeze
13
+
14
+ HUNDREDS = [nil, "сто", "двести", "триста", "четыреста", "пятьсот",
15
+ "шестьсот", "семьсот", "восемьсот", "девятьсот"].freeze
16
+
17
+ # формы: [one, few, many]
18
+ SCALES = [
19
+ ["", "", ""], # 10^0 (единицы)
20
+ %w[тысяча тысячи тысяч], # 10^3
21
+ %w[миллион миллиона миллионов], # 10^6
22
+ %w[миллиард миллиарда миллиардов], # 10^9
23
+ %w[триллион триллиона триллионов] # 10^12
24
+ ].freeze
25
+
26
+ RUB = %w[рубль рубля рублей].freeze
27
+ KOP = %w[копейка копейки копеек].freeze
28
+
29
+ class << self
30
+ def pluralize(n, one, few, many)
31
+ return many if (11..14).include?(n % 100)
32
+ case n % 10
33
+ when 1 then one
34
+ when 2..4 then few
35
+ else many
36
+ end
37
+ end
38
+
39
+ # n — 0..999, scale_idx — индекс разряда (0 — единицы, 1 — тысячи, ...)
40
+ # feminine: true — использовать женский род для единиц (нужно для тысяч/копеек)
41
+ def triple_to_words(n, scale_idx, feminine: false)
42
+ return [] if n.zero?
43
+
44
+ words = []
45
+ words << HUNDREDS[n / 100] if n >= 100
46
+
47
+ rest = n % 100
48
+ if rest.between?(10, 19)
49
+ words << TEENS[rest - 10]
50
+ else
51
+ words << TENS[rest / 10] if rest >= 20
52
+ ones = rest % 10
53
+ if ones.positive?
54
+ words << (feminine ? ONES_FEM[ones] : ONES_MASC[ones])
55
+ end
56
+ end
57
+
58
+ # добавляем наименование разряда (кроме единиц)
59
+ words << pluralize(n, *SCALES[scale_idx]) unless scale_idx.zero?
60
+ words.compact
61
+ end
62
+
63
+ # number — целое число (0..10^12-1)
64
+ def to_words(number, feminine: false)
65
+ number = Integer(number)
66
+ return (feminine ? ONES_FEM[0] : ONES_MASC[0]) if number.zero?
67
+
68
+ groups = number.to_s
69
+ .chars.reverse.each_slice(3).map(&:reverse)
70
+ .map(&:join).map!(&:to_i).reverse
71
+
72
+ words = []
73
+ groups.each_with_index do |grp, idx|
74
+ scale_idx = groups.size - idx - 1
75
+ fem = (scale_idx == 1) || feminine # тысячи — жен. род
76
+ words.concat triple_to_words(grp, scale_idx, feminine: fem)
77
+ end
78
+ words.join(" ")
79
+ end
80
+
81
+ # amount может быть String, Integer, Float, BigDecimal
82
+ def to_currency(amount)
83
+ str = amount.to_s
84
+ rub_str, kop_str = str.split(".")
85
+ rub = Integer(rub_str)
86
+ # всегда 2 знака для копеек; обрезаем лишние, дополняем недостающие
87
+ kop = (kop_str || "0")[0, 2].ljust(2, "0").to_i
88
+
89
+ rub_words = to_words(rub)
90
+ rub_name = pluralize(rub, *RUB)
91
+
92
+ kop_words = to_words(kop, feminine: true)
93
+ kop_name = pluralize(kop, *KOP)
94
+
95
+ "#{rub_words} #{rub_name} #{kop_words} #{kop_name}"
96
+ end
97
+ end
98
+ end
99
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Integer
4
+ def to_words(feminine: false)
5
+ Num2words::Converter.to_words(self, feminine: feminine)
6
+ end
7
+
8
+ def to_currency
9
+ Num2words::Converter.to_currency(self)
10
+ end
11
+ end
12
+
13
+ class Float
14
+ def to_currency
15
+ Num2words::Converter.to_currency(self)
16
+ end
17
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Num2words
4
+ VERSION = "0.1.0"
5
+ end
data/lib/num2words.rb ADDED
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "num2words/version"
4
+ require_relative "num2words/converter"
5
+ require_relative "num2words/core_ext"
6
+
7
+ module Num2words
8
+ def self.to_words(number, feminine: false)
9
+ Converter.to_words(number, feminine: feminine)
10
+ end
11
+
12
+ def self.to_currency(amount)
13
+ Converter.to_currency(amount)
14
+ end
15
+ end
data/num2words.gemspec ADDED
@@ -0,0 +1,27 @@
1
+ require_relative 'lib/num2words/version'
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = "num2words"
5
+ spec.version = Num2words::VERSION
6
+ spec.authors = ["Ruslan Fedotov"]
7
+ spec.email = ["progruson@gmail.com"]
8
+
9
+ spec.summary = %q{Russian number-to-words with currency (руб/коп) and correct declensions}
10
+ spec.description = %q{Converts integers and amounts to Russian words with proper gender and plural forms.}
11
+ spec.homepage = "https://github.com/skyrusx/num2words"
12
+ spec.license = "MIT"
13
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
14
+
15
+ spec.metadata["homepage_uri"] = spec.homepage
16
+ spec.metadata["source_code_uri"] = spec.homepage
17
+ spec.metadata["changelog_uri"] = spec.homepage + "/blob/main/CHANGELOG.md"
18
+
19
+ # Specify which files should be added to the gem when it is released.
20
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
21
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
22
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
23
+ end
24
+ spec.bindir = "exe"
25
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
26
+ spec.require_paths = ["lib"]
27
+ end
metadata ADDED
@@ -0,0 +1,59 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: num2words
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Ruslan Fedotov
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2025-08-18 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Converts integers and amounts to Russian words with proper gender and
14
+ plural forms.
15
+ email:
16
+ - progruson@gmail.com
17
+ executables: []
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - ".gitignore"
22
+ - Gemfile
23
+ - LICENSE.txt
24
+ - README.md
25
+ - Rakefile
26
+ - bin/console
27
+ - bin/setup
28
+ - lib/num2words.rb
29
+ - lib/num2words/converter.rb
30
+ - lib/num2words/core_ext.rb
31
+ - lib/num2words/version.rb
32
+ - num2words.gemspec
33
+ homepage: https://github.com/skyrusx/num2words
34
+ licenses:
35
+ - MIT
36
+ metadata:
37
+ homepage_uri: https://github.com/skyrusx/num2words
38
+ source_code_uri: https://github.com/skyrusx/num2words
39
+ changelog_uri: https://github.com/skyrusx/num2words/blob/main/CHANGELOG.md
40
+ post_install_message:
41
+ rdoc_options: []
42
+ require_paths:
43
+ - lib
44
+ required_ruby_version: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - ">="
47
+ - !ruby/object:Gem::Version
48
+ version: 2.3.0
49
+ required_rubygems_version: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - ">="
52
+ - !ruby/object:Gem::Version
53
+ version: '0'
54
+ requirements: []
55
+ rubygems_version: 3.1.2
56
+ signing_key:
57
+ specification_version: 4
58
+ summary: Russian number-to-words with currency (руб/коп) and correct declensions
59
+ test_files: []