.jpg)
Variables
Variables in Ruby are used to store values that can be accessed and manipulated throughout your program. You can think of a variable as a named container that holds a value.In Ruby, variable names must begin with a lowercase letter or underscore, and can contain letters, numbers, and underscores. Here's an example of defining a variable:
name = "Alice"
In this code, we're defining a variable called name and assigning it the value "Alice". We can then use this variable later in our program, like this:
puts "Hello, #{name}!"
This code will print the message "Hello, Alice!", using the value stored in the name variable.
Ruby is a dynamically-typed language, which means that the type of a variable is determined at runtime based on the value it holds. For example, we could define a variable like this:
age = 30
In this case, the age variable holds an integer value, so its type is Fixnum.
Constants
Constants in Ruby are similar to variables, but their value cannot be changed once they have been defined. Constants are used for values that are intended to remain constant throughout your program, such as mathematical constants, configuration settings, and API keys.In Ruby, constant names must begin with an uppercase letter. Here's an example of defining a constant:
PI = 3.14159
In this code, we're defining a constant called PI and assigning it the value 3.14159. Once a constant has been defined, its value cannot be changed:
PI = 3.14 # This will raise a warning or error
It's important to note that while Ruby prevents you from changing the value of a constant, it doesn't prevent you from changing the value of an object that the constant refers to. For example:
MY_ARRAY = [1, 2, 3] MY_ARRAY.push(4) # This is allowed
In this code, we're defining a constant called MY_ARRAY and assigning it an array. While we can't change the value of MY_ARRAY itself, we can modify the contents of the array it refers to.
0 Comments