Custom implementation of String's to_i method
require_relative 'string'
"123".my_to_i # 123
"123a45".my_to_i # 123
"123.123".my_to_i # 123
"aaaaa".my_to_i # 0
"-123".my_to_i # -123rspec string_spec.rb
| class String | |
| INT_LOOKUP = { "1" => 1, "2" => 2, "3" => 3, "4" => 4, "5" => 5, "6" => 6, "7" => 7, "8" => 8, "9" => 9, "0" => 0, "-" => -1 } | |
| def clean_i | |
| integer = self.split('.')[0] | |
| to_convert = [] | |
| integer.split('').each do |i| | |
| break if INT_LOOKUP[i].nil? | |
| to_convert << INT_LOOKUP[i] | |
| end | |
| to_convert | |
| end | |
| def my_to_i | |
| clean_i.reverse.each_with_index.reduce(0) do |acc, (int, index)| | |
| if int == -1 | |
| acc * -1 | |
| else | |
| tens = 1 | |
| index.times { |_| | |
| tens = tens * 10 | |
| } | |
| acc + ( int * tens ) | |
| end | |
| end | |
| end | |
| end |
| require 'rspec' | |
| require_relative 'string' | |
| RSpec.describe String do | |
| context 'converts string of positive number to int' do | |
| it 'without special characters' do | |
| expect("123".my_to_i).to eq("123".to_i) | |
| end | |
| it 'with alphabet characters' do | |
| expect("123a".my_to_i).to eq("123a".to_i) | |
| expect("123a45".my_to_i).to eq("123a45".to_i) | |
| end | |
| it 'with decimal' do | |
| expect("123.123".my_to_i).to eq("123.123".to_i) | |
| end | |
| it 'with only letters' do | |
| expect("aaaaa".my_to_i).to eq("aaaaa".to_i) | |
| end | |
| end | |
| context 'converts string of negative number to int' do | |
| it 'without special characters' do | |
| expect("-123".my_to_i).to eq("-123".to_i) | |
| end | |
| it 'with alphabet characters' do | |
| expect("-123a".my_to_i).to eq("-123a".to_i) | |
| expect("-123a45".my_to_i).to eq("-123a45".to_i) | |
| end | |
| it 'with decimal' do | |
| expect("-123.123".my_to_i).to eq("-123.123".to_i) | |
| end | |
| it 'with only letters' do | |
| expect("-aaaaa".my_to_i).to eq("-aaaaa".to_i) | |
| end | |
| end | |
| end |