0
0
Rubyprogramming~5 mins

Dynamic typing vs strong typing in Ruby

Choose your learning style9 modes available
Introduction

We use dynamic and strong typing to help the computer understand and check the types of data while running programs. This helps catch mistakes and makes coding easier.

When you want to write code quickly without declaring types explicitly.
When you want the computer to check that you don't mix incompatible data types.
When you want flexibility to change data types during program execution.
When you want to avoid bugs caused by wrong data types.
When you want the program to be easy to read and write without extra type rules.
Syntax
Ruby
# Ruby is dynamically typed and strongly typed
x = 5       # x is an integer now
x = "Hi"   # x is now a string

# Trying to add a number and a string causes an error
5 + "5"    # TypeError

Dynamic typing means you don't have to say the type of a variable before using it.

Strong typing means the language checks types and won't let you mix incompatible types without explicit conversion.

Examples
You can change the type of variable a anytime because Ruby is dynamically typed.
Ruby
a = 10
puts a.class  # Output: Integer

a = "hello"
puts a.class  # Output: String
Ruby does not allow adding a number and a string directly because it is strongly typed.
Ruby
puts 5 + 3      # Output: 8
puts 5 + "3"    # Raises TypeError
Sample Program

This program shows how Ruby lets you change the type of a variable easily (dynamic typing). But if you try to add a number and a string, Ruby will stop you with an error (strong typing).

Ruby
x = 7
puts "x is a #{x.class} with value #{x}"
x = "seven"
puts "Now x is a #{x.class} with value #{x}"

# This will cause an error:
# puts 5 + "5"
OutputSuccess
Important Notes

Dynamic typing makes coding faster but you must be careful with data types.

Strong typing helps catch errors early by preventing wrong type operations.

In Ruby, you can convert types explicitly, for example: 5 + "5".to_i works fine.

Summary

Dynamic typing means variables can hold any type and change types anytime.

Strong typing means the language checks types and stops you from mixing incompatible types without conversion.

Ruby is both dynamically typed and strongly typed, giving flexibility and safety.