Ruby Tutorial
Ruby CGI
Ruby Advanced
Ruby is a dynamic, object-oriented programming language. It has several data types to store different types of data. The main data types in Ruby are:
Let's go over each of these in detail:
1. Numbers:
Ruby supports integers, floating point numbers, and complex numbers. Here's an example:
integer = 10 float = 10.5 complex = Complex(1) puts integer, float, complex
2. Strings:
Strings are sequences of characters. They can be defined using single or double quotes. Double quoted strings can interpret escape sequences and interpolation.
single_quoted = 'Hello, World!' double_quoted = "Hello, #{single_quoted}" puts single_quoted, double_quoted
3. Symbols:
Symbols are lightweight, immutable strings. They are often used as keys in hashes or for referencing method names.
symbol = :hello puts symbol
4. Arrays:
Arrays are ordered collections. They can hold any type of object, and you can access their elements with an index.
array = [1, 'two', :three] puts array[0] # outputs: 1
5. Hashes:
Hashes are collections of key-value pairs. The keys can be any object, but symbols are commonly used.
hash = { one: 1, 'two' => 2, :three => 3 } puts hash[:one] # outputs: 1 puts hash['two'] # outputs: 2
6. Booleans:
Ruby has two boolean values: true
and false
.
is_true = true is_false = false puts is_true, is_false
7. Nil:
nil
in Ruby is used to express the absence of a value. It's equivalent to null
in other languages.
nothing = nil puts nothing # outputs:
These are the basic data types in Ruby. Remember, everything in Ruby is an object, even basic data types like numbers or strings, so you can call methods on them just like any other object. For example, "Hello, World!".length
will return 13, the number of characters in the string.
Ruby integer data type:
my_integer = 42
Ruby float data type:
my_float = 3.14
Ruby string data type:
my_string = "Hello, Ruby!"
Ruby array data type:
my_array = [1, 2, 3, 4]
Ruby hash data type:
my_hash = { "name" => "John", "age" => 25 }
Ruby boolean data type:
my_boolean = true
Ruby symbol data type:
my_symbol = :my_symbol
Ruby nil data type:
nil
represents the absence of a value in Ruby.my_nil = nil
Ruby data type conversion:
my_integer = 42 my_string = my_integer.to_s
Ruby dynamic typing:
my_variable = 42 puts my_variable my_variable = "Hello, Ruby!" puts my_variable
Ruby class as a data type:
class Person attr_accessor :name, :age def initialize(name, age) @name = name @age = age end end person = Person.new("John", 25)
Ruby complex data types:
# Struct Point = Struct.new(:x, :y) point = Point.new(1, 2) # Range my_range = (1..5) # Regular Expression regex = /pattern/
Ruby data type checking:
is_a?
or kind_of?
for data type checking in Ruby.my_variable = "Hello, Ruby!" if my_variable.is_a?(String) puts "It's a string!" else puts "It's not a string." end