← homeProgramming (Програмування)

What will be the result of adding 10.5 and 10?

A popular interview question for a junior position. What will be the result of adding 10.5 and 10?

This content has been automatically translated from Ukrainian.
A seemingly simple question can come up 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 there is a decimal point - 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 adding 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 a 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.

🔥 More posts

All posts
Scope of a local variable in Ruby
Programming (Програмування)Jun 3, '24 16:46

Scope of a local variable in Ruby

The scope of local variables in Ruby. Examples of how variable visibility works in Ruby.

What is immutability and mutability?
Programming (Програмування)Jun 19, '24 07:48

What is immutability and mutability?

What is immutability and mutability? A description of the term in the context of programming and ...

What is a function in programming?
Programming (Програмування)Jun 24, '24 18:15

What is a function in programming?

What is a function in programming? Example of a function in Ruby and JavaScript

How to make an empty git commit?
Programming (Програмування)Jun 28, '24 08:33

How to make an empty git commit?

How to make an empty git commit? Let's make an empty git commit. Why? Who knows, everyone has the...

Ruby library Gosu for creating 2D games
Programming (Програмування)Jun 29, '24 08:48

Ruby library Gosu for creating 2D games

Ruby library Gosu for creating 2D games. Description of the library for game development in Ruby ...