This content has been automatically translated from Ukrainian.
A seemingly simple question can arise in an interview for a junior ruby dev position. What will be the result of adding 10.5 and 10? What's the catch?
10.5 + 10
Let's break down the example. What is the difference between 10.5 and 10? Notice the .5, that is, the floating point. Let's check the classes of these two objects.
10.5.class => Float 10.class => Integer
And here lies the catch. We are adding objects of two classes. What will be the result if we add Float and Integer?
(10.5 + 10).class => Float
So after adding Float and Integer, we will get Float. What does this mean? It means that when a decimal point is present, the result will have a decimal point.
10.5 + 10 => 20.5
To prove this, we can write tests. We will also check if we get an object of class Integer when we add 10 + 10.
Let's create a file operations_spec.rb:
require 'rspec'
RSpec.describe 'Addition operations' do
context 'when adding Float and Integer' do
it 'returns Float' do
result = 10.5 + 10
expect(result).to be_a(Float)
expect(result).to eq(20.5)
end
end
context 'when adding Integer and Integer' do
it 'returns Integer' do
result = 10 + 10
expect(result).to be_a(Integer)
expect(result).to eq(20)
end
end
end
We run it and get the result that confirms everything we wrote above.
rspec operations_spec.rb .. Finished in 0.01617 seconds (files took 0.31407 seconds to load) 2 examples, 0 failures
Everything is quite simple. But you need to know these nuances.
This post doesn't have any additions from the author yet.