Skip to content

Instantly share code, notes, and snippets.

@mrryanjohnston
Last active June 20, 2018 01:09
Show Gist options
  • Save mrryanjohnston/8f2f6e18553087a2a889a1fcfdffebb0 to your computer and use it in GitHub Desktop.
Save mrryanjohnston/8f2f6e18553087a2a889a1fcfdffebb0 to your computer and use it in GitHub Desktop.
my_to_i

String#my_to_i

Description

Custom implementation of String's to_i method

Usage

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 # -123

Testing

rspec 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment