Ruby, a dynamic and object-oriented programming language, offers a variety of data types to represent different kinds of information. Understanding these data types is crucial for effective Ruby programming.
Ruby supports integers and floating-point numbers:
# Integer
age = 30
# Float
pi = 3.14159
Strings in Ruby are sequences of characters enclosed in single or double quotes:
name = "Ruby"
greeting = 'Hello, World!'
Boolean values in Ruby are represented by true
and false
:
is_ruby_fun = true
is_coding_boring = false
Arrays are ordered collections of objects. They can contain mixed data types:
fruits = ["apple", "banana", "cherry"]
mixed_array = [1, "two", 3.0, true]
Learn more about Ruby Arrays and their methods.
Hashes are collections of key-value pairs:
person = { "name" => "Alice", "age" => 30, "city" => "New York" }
Explore Ruby Hashes for advanced usage and methods.
Symbols are lightweight, immutable identifiers:
status = :active
role = :admin
Dive deeper into Ruby Symbols to understand their benefits and use cases.
nil
represents the absence of a value:
empty_variable = nil
Ranges represent sequences of values:
number_range = 1..10 # Inclusive range
letter_range = 'a'...'z' # Exclusive range
Learn more about Ruby Ranges and their applications.
Ruby provides methods to check and convert between data types:
# Type checking
puts 42.is_a?(Integer) # true
puts "Hello".is_a?(String) # true
# Type conversion
puts "42".to_i # 42 (string to integer)
puts 3.14.to_s # "3.14" (float to string)
Understanding Ruby's data types is fundamental to writing efficient and error-free code. As you progress, explore more advanced concepts like Ruby Objects and Ruby Modules to enhance your Ruby programming skills.