From 1446501c9048f5e03c2d5d50416e3fbe1b21236e Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Sun, 7 Nov 2021 01:14:20 +0900 Subject: [PATCH] Make `Node#numeric_type?` aware of rational and complex literals This PR makes `Node#numeric_type?` aware of complex and rational literals. These literals could be treated as numeric. ```ruby 42r.is_a?(Numeric) # => true 42i.is_a?(Numeric) # => true 42ri.is_a?(Numeric) # => true ``` --- ...predicate_aware_of_rational_and_complex.md | 1 + lib/rubocop/ast/node.rb | 2 +- spec/rubocop/ast/node_spec.rb | 50 +++++++++++++++++++ 3 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 changelog/new_make_numeric_type_predicate_aware_of_rational_and_complex.md diff --git a/changelog/new_make_numeric_type_predicate_aware_of_rational_and_complex.md b/changelog/new_make_numeric_type_predicate_aware_of_rational_and_complex.md new file mode 100644 index 000000000..2e0ff1373 --- /dev/null +++ b/changelog/new_make_numeric_type_predicate_aware_of_rational_and_complex.md @@ -0,0 +1 @@ +* [#213](https://github.com/rubocop/rubocop-ast/pull/213): Make `Node#numeric_type?` aware of rational and complex literals. ([@koic][]) diff --git a/lib/rubocop/ast/node.rb b/lib/rubocop/ast/node.rb index f37e5e74f..9e3148efa 100644 --- a/lib/rubocop/ast/node.rb +++ b/lib/rubocop/ast/node.rb @@ -464,7 +464,7 @@ def boolean_type? end def numeric_type? - int_type? || float_type? + int_type? || float_type? || rational_type? || complex_type? end def range_type? diff --git a/spec/rubocop/ast/node_spec.rb b/spec/rubocop/ast/node_spec.rb index 47b774d95..c30113bd0 100644 --- a/spec/rubocop/ast/node_spec.rb +++ b/spec/rubocop/ast/node_spec.rb @@ -786,4 +786,54 @@ class << expr it { is_expected.to eq nil } end end + + describe '#nurimec_type?' do + context 'when integer literal' do + let(:src) { '42' } + + it 'is true' do + expect(node).to be_numeric_type + end + end + + context 'when float literal' do + let(:src) { '42.0' } + + it 'is true' do + expect(node).to be_numeric_type + end + end + + context 'when rational literal' do + let(:src) { '42r' } + + it 'is true' do + expect(node).to be_numeric_type + end + end + + context 'when complex literal' do + let(:src) { '42i' } + + it 'is true' do + expect(node).to be_numeric_type + end + end + + context 'when complex literal whose imaginary part is a rational' do + let(:src) { '42ri' } + + it 'is true' do + expect(node).to be_numeric_type + end + end + + context 'when string literal' do + let(:src) { '"42"' } + + it 'is true' do + expect(node).not_to be_numeric_type + end + end + end end