Ruby Arrays

This chapter covers ruby-arrays , a versatile data structure used to store ordered collections of elements. Arrays in Ruby can hold any data type, including other arrays, enabling the creation of complex, nested structures.

Chapter Goals

  • Understand the purpose and syntax of arrays in Ruby.
  • Learn how to create, access, and manipulate arrays.
  • Explore various methods for array operations.
  • Implement best practices for working with arrays in Ruby.

Key Characteristics of Ruby Arrays

  • Dynamic Sizing: Arrays grow or shrink dynamically as elements are added or removed.
  • Flexible Data Types: Can store elements of mixed data types.
  • Zero-Based Indexing: Indexes start from 0 for the first element.
  • Enumerable Methods: Provides powerful methods for iteration, searching, and transformation.

Basic Rules for Ruby Arrays

  • Use square brackets ([]) to define arrays.
  • Access elements using their index (starting from 0).
  • Negative indexing can retrieve elements from the end of the array.
  • Modify arrays using methods like push, pop, shift, and unshift.

Best Practices

  • Use arrays for ordered collections where element sequence matters.
  • Prefer iterators (each, map, select) for concise and expressive code.
  • Avoid excessive nesting for better readability and maintainability.
  • Use freeze to create immutable arrays when the content should not change.
  • Document complex array manipulations for better understanding.

Syntax Table

Serial No Feature Syntax/Example Description
1 Create an Array numbers = [1, 2, 3] Defines a simple array.
2 Access Elements numbers[0] Retrieves the first element of the array.
3 Add Elements numbers.push(4) Appends an element to the array.
4 Remove Elements numbers.pop Removes the last element of the array.
5 Array Methods numbers.sort Applies operations like sorting.

Syntax Explanation

1. Create an Array

What is Creating an Array?

Arrays are collections of elements stored in a specific order.

Syntax

numbers = [1, 2, 3]

Detailed Explanation

  • Created using square brackets ([]).
  • Elements are separated by commas.
  • Can hold elements of any data type, including strings, numbers, and other arrays.
  • Arrays can be empty ([]) or initialized with default values.

Example

fruits = [“apple”, “banana”, “cherry”]

puts fruits

Example Explanation

  • Creates an array fruits with three elements.
  • Outputs apple, banana, and cherry.

2. Access Elements

What is Accessing Elements?

Elements in an array are accessed by their index.

Syntax

numbers[0]

Detailed Explanation

  • Indexing starts from 0 for the first element.
  • Negative indexing starts from -1 for the last element.
  • Accessing an out-of-bound index returns nil.

Example

fruits = [“apple”, “banana”, “cherry”]

puts fruits[1]

Example Explanation

  • Retrieves the second element banana using its index.

3. Add Elements

What is Adding Elements?

Adding elements modifies the array to include new items.

Syntax

numbers.push(4)

Detailed Explanation

  • Use push to add an element to the end of the array.
  • Use unshift to add an element to the beginning.
  • Arrays grow dynamically to accommodate new elements.

Example

fruits = [“apple”, “banana”]

fruits.push(“cherry”)

puts fruits

Example Explanation

  • Adds cherry to the end of the fruits array.
  • Outputs [“apple”, “banana”, “cherry”].

4. Remove Elements

What is Removing Elements?

Elements can be removed from the array dynamically.

Syntax

numbers.pop

Detailed Explanation

  • Use pop to remove the last element.
  • Use shift to remove the first element.
  • Removing elements modifies the array size accordingly.

Example

fruits = [“apple”, “banana”, “cherry”]

fruits.pop

puts fruits

Example Explanation

  • Removes the last element cherry.
  • Outputs [“apple”, “banana”].

5. Array Methods

What are Array Methods?

Ruby provides a range of methods to manipulate arrays effectively.

Syntax

numbers.sort

Detailed Explanation

  • Methods include sort, reverse, uniq, map, select, and more.
  • These methods can transform, filter, or query arrays.
  • Methods like map and select return new arrays based on the operation.

Example

numbers = [3, 1, 2]

sorted_numbers = numbers.sort

puts sorted_numbers

Example Explanation

  • Sorts the numbers array in ascending order.
  • Outputs [1, 2, 3].

Real-Life Project

Project Name: To-Do List Manager

Project Goal

Create a program to manage a dynamic to-do list using arrays.

Code for This Project

def add_task(tasks, task)

  tasks.push(task)

  puts “Added: \#{task}”

end

 

def remove_task(tasks)

  removed_task = tasks.pop

  puts “Removed: \#{removed_task}”

end

 

def list_tasks(tasks)

  puts “Your Tasks:”

  tasks.each_with_index { |task, index| puts “\#{index + 1}. \#{task}” }

end

 

tasks = []

add_task(tasks, “Learn Ruby”)

add_task(tasks, “Write Code”)

list_tasks(tasks)

remove_task(tasks)

list_tasks(tasks)

Steps

  1. Define methods to add, remove, and list tasks.
  2. Use an array tasks to store the tasks dynamically.
  3. Call the methods to interact with the task list.

Expected Output

Added: Learn Ruby

Added: Write Code

Your Tasks:

  1. Learn Ruby
  2. Write Code

Removed: Write Code

Your Tasks:

  1. Learn Ruby

Project Explanation

  • Demonstrates dynamic addition and removal of array elements.
  • Uses iterators to display tasks with indexing.

Insights

Ruby arrays are a powerful and flexible tool for managing collections of data. Mastering their methods and best practices enables efficient and elegant solutions to various problems.

Key Takeaways

  • Leverage arrays for ordered collections and use appropriate methods for modifications.
  • Explore Ruby’s array methods for efficient transformations and queries.
  • Avoid unnecessary nesting for better readability and simplicity.
  • Use arrays dynamically to build interactive and responsive programs.

Ruby Constants

This chapter focuses on ruby-constants , essential elements in programming used to store values that should not change during the execution of a program. Constants play a vital role in maintaining code clarity and preventing unintended value modifications.

Chapter Goals

  • Understand the purpose and usage of constants in Ruby.
  • Learn about the conventions and rules for defining constants.
  • Explore scenarios and best practices for working with constants.

Key Characteristics of Ruby Constants

  • Immutable by Convention: Constants are designed to hold values that remain unchanged, though reassignment is possible with warnings.
  • Global Accessibility: Constants can be accessed from various parts of a program, depending on their scope.
  • Case Sensitivity: Constants are case-sensitive and must begin with an uppercase letter.
  • Readability: Enhance code clarity by giving meaningful names to unchanging values.

Basic Rules for Ruby Constants

  • Define constants with meaningful, descriptive names in UPPER_SNAKE_CASE.
  • Avoid reassigning constants to preserve their intended immutability.
  • Use constants for fixed values such as configuration settings, mathematical constants, or file paths.
  • Place constants in appropriate scopes (classes, modules, or globally) to ensure clear access and usage.

Best Practices

  • Use constants instead of magic numbers or strings for better code readability.
  • Group related constants within modules or classes.
  • Avoid modifying constants to maintain their integrity.
  • Use freeze for objects stored in constants to make them fully immutable.
  • Document constants in the code for easy understanding of their purpose.

Syntax Table

Serial No Feature Syntax/Example Description
1 Define a Constant PI = 3.14 Creates a constant for the value of Pi.
2 Access a Constant puts PI Outputs the value of the constant.
3 Constant in Module Math::PI Accesses a constant within a module.
4 Freeze an Object URLS = [].freeze Makes an array immutable.
5 Reassign a Constant PI = 3.14159 Issues a warning but allows reassignment.

Syntax Explanation

1. Define a Constant

What is Defining a Constant?

Defining a constant creates a named reference to a value that is intended to remain unchanged throughout the program.

Syntax

PI = 3.14

Detailed Explanation

  • Constants must begin with an uppercase letter.
  • Can store any data type, including numbers, strings, arrays, or hashes.
  • Typically used for unchanging values like configuration settings, mathematical constants, or default options.
  • Constants are globally accessible if defined outside of any class or module.

Example

MAX_USERS = 100

puts “Maximum users allowed: #{MAX_USERS}”

Example Explanation

  • Defines a constant MAX_USERS with the value 100.
  • Outputs “Maximum users allowed: 100” using string interpolation.

2. Access a Constant

What is Accessing a Constant?

Constants can be accessed directly by their name or through their module/class scope.

Syntax

puts PI

Detailed Explanation

  • Constants defined globally can be accessed anywhere in the program.
  • Constants defined in a module or class require their fully qualified name (e.g., Module::CONSTANT).
  • Accessing a constant does not alter its value.

Example

class Config

  DEFAULT_TIMEOUT = 30

end

 

puts Config::DEFAULT_TIMEOUT

Example Explanation

  • Defines a constant DEFAULT_TIMEOUT within the Config class.
  • Accesses the constant using the scope resolution operator (::).

3. Constant in Module

What is a Constant in a Module?

Modules can encapsulate related constants, providing a namespace to prevent naming conflicts.

Syntax

module Math

  PI = 3.14

end

 

puts Math::PI

Detailed Explanation

  • Constants in a module are accessed using the scope resolution operator (::).
  • Encapsulation helps organize constants logically and avoid conflicts.

Example

module AppSettings

  APP_NAME = “MyApp”

end

 

puts AppSettings::APP_NAME

Example Explanation

  • Defines a constant APP_NAME within the AppSettings module.
  • Accesses it using AppSettings::APP_NAME.

4. Freeze an Object

What is Freezing an Object?

Freezing a constant ensures that the object it references cannot be modified, making it fully immutable.

Syntax

URLS = [].freeze

Detailed Explanation

  • Freezing a constant prevents modification of the object it references.
  • Adds an additional layer of immutability to ensure data integrity.
  • Commonly used with collections like arrays and hashes.

Example

DEFAULT_OPTIONS = { retries: 3, timeout: 30 }.freeze

puts DEFAULT_OPTIONS[:retries]

Example Explanation

  • Defines a constant DEFAULT_OPTIONS as a frozen hash.
  • Accessing elements of the hash does not alter its immutability.

5. Reassign a Constant

What is Reassigning a Constant?

Although constants are meant to remain unchanged, Ruby allows reassignment with a warning.

Syntax

PI = 3.14159

Detailed Explanation

  • Reassigning a constant generates a warning but does not raise an error.
  • It is discouraged to reassign constants as it contradicts their purpose.
  • Used sparingly in scenarios requiring unavoidable overrides.

Example

MAX_USERS = 100

MAX_USERS = 200

puts MAX_USERS

Example Explanation

  • Reassigns MAX_USERS from 100 to 200 with a warning.
  • Outputs 200, demonstrating the reassignment capability.

Real-Life Project

Project Name: Application Configuration Manager

Project Goal

Create a configuration manager that organizes application settings using constants.

Code for This Project

module Config

  APP_NAME = “MyApp”

  DEFAULT_TIMEOUT = 60

  RETRY_LIMIT = 3

 

  def self.display

    puts “App Name: #{APP_NAME}”

    puts “Default Timeout: #{DEFAULT_TIMEOUT} seconds”

    puts “Retry Limit: #{RETRY_LIMIT}”

  end

end

 

Config.display

Steps

  1. Define a module Config to encapsulate constants.
  2. Add constants for application settings like APP_NAME, DEFAULT_TIMEOUT, and RETRY_LIMIT.
  3. Create a method display to output the configuration.

Expected Output

App Name: MyApp

Default Timeout: 60 seconds

Retry Limit: 3

Project Explanation

  • Demonstrates grouping constants logically within a module.
  • Highlights the use of constants for configuration and easy access.

Insights

Ruby constants help maintain consistency and clarity in programs. Adhering to their conventions and best practices ensures better readability and maintainability.

Key Takeaways

  • Use meaningful, descriptive names for constants in UPPER_SNAKE_CASE.
  • Place constants within appropriate scopes for logical grouping and access.
  • Avoid modifying constants to preserve their integrity.
  • Leverage freeze to make objects referenced by constants immutable.

 Ruby Data Types

This chapter delves into ruby-data-types , essential components for handling and manipulating data in programming. Ruby provides a rich set of data types that cater to various needs, including numbers, strings, arrays, hashes, and more. Understanding these data types is fundamental for writing efficient and expressive Ruby code.

Chapter Goals

  • Understand the different data types in Ruby.
  • Learn how to create and manipulate data types.
  • Explore the use cases and properties of each data type.
  • Implement best practices for working with Ruby data types.

Key Characteristics of Ruby Data Types

  • Dynamic Typing: Variables can hold any data type, and the type can change during runtime.
  • Rich Standard Library: Includes numerous methods for manipulating data types.
  • Object-Oriented: Every data type is an object, enabling method chaining and easy interaction.
  • Flexible and Intuitive: Simple syntax for creating and working with data types.

Basic Rules for Ruby Data Types

  • Use appropriate data types for the task to ensure code clarity and performance.
  • Leverage Ruby’s built-in methods for efficient data manipulation.
  • Avoid mixing data types in a way that can lead to errors or unexpected behavior.
  • Utilize symbols for immutable identifiers and strings for dynamic text.

Best Practices

  • Prefer symbols over strings for keys in hashes when keys are immutable.
  • Use arrays for ordered collections and hashes for key-value pairs.
  • Leverage enumerables and iterators for concise and expressive code.
  • Validate and sanitize user input to prevent type-related errors.
  • Use Ruby’s built-in type conversion methods (to_i, to_s, to_a, etc.) judiciously.

Syntax Table

Serial No Data Type Syntax/Example Description
1 Integer age = 25 Whole numbers, positive or negative.
2 Float pi = 3.14 Decimal numbers.
3 String name = “Ruby” Sequence of characters.
4 Symbol status = :active Immutable identifiers.
5 Array numbers = [1, 2, 3] Ordered collection of elements.
6 Hash user = {name: “Alice”} Key-value pairs.
7 Boolean flag = true Represents true or false.
8 Nil value = nil Represents absence of value.

Syntax Explanation

1. Integer

What is an Integer?

Integers are whole numbers, either positive or negative, used for arithmetic and counting.

Syntax

age = 25

Detailed Explanation

  • Represented without any decimal point.
  • Supports standard arithmetic operations like addition, subtraction, multiplication, and division.
  • Can store very large numbers, as Ruby dynamically adjusts their size.
  • Used in loops, counters, and general numeric calculations.

Example

items_count = 10

puts “Total items: #{items_count}”

Example Explanation

  • Assigns 10 to the variable items_count.
  • Outputs “Total items: 10” using string interpolation.
  • Demonstrates assignment and use in a string context.

2. Float

What is a Float?

Floats are numbers with a decimal point, used for precise calculations and representing fractions.

Syntax

pi = 3.14

Detailed Explanation

  • Represented with a decimal point.
  • Useful for operations requiring precision, such as financial or scientific calculations.
  • Supports all arithmetic operations and can interact seamlessly with integers in expressions.

Example

price = 19.99

puts “Total price: $#{price}”

Example Explanation

  • Assigns 19.99 to the variable price.
  • Outputs “Total price: $19.99”.
  • Illustrates usage in a real-world scenario like pricing.

3. String

What is a String?

Strings are sequences of characters used to represent text.

Syntax

name = “Ruby”

Detailed Explanation

  • Can be created using double quotes (“”) or single quotes ().
  • Supports numerous methods for manipulation, such as concatenation, slicing, and formatting.
  • Strings are mutable, allowing for modifications after creation.
  • Commonly used in input/output operations, file handling, and dynamic content generation.

Example

greeting = “Hello”

name = “Alice”

puts “#{greeting}, #{name}!”

Example Explanation

  • Combines multiple strings using string interpolation.
  • Outputs “Hello, Alice!”.
  • Highlights the dynamic and flexible nature of Ruby strings.

4. Symbol

What is a Symbol?

Symbols are immutable, lightweight identifiers often used in hashes and for representing state or options.

Syntax

status = :active

Detailed Explanation

  • Prefixed with a colon (:).
  • Immutable, meaning they cannot be modified once created.
  • More memory-efficient than strings when used as keys or identifiers.
  • Commonly used for situations where the value does not change, such as hash keys or method names.

Example

user_status = :active

puts “User is #{user_status}”

Example Explanation

  • Assigns :active to user_status.
  • Outputs “User is active”.
  • Demonstrates use as a state identifier.

5. Array

What is an Array?

Arrays are ordered collections of elements, which can be of any data type.

Syntax

numbers = [1, 2, 3]

Detailed Explanation

  • Created using square brackets ([]).
  • Elements are indexed starting from 0.
  • Supports a variety of operations like addition, deletion, and iteration.
  • Flexible enough to hold mixed data types within a single array.
  • Arrays can be nested, allowing for multi-dimensional structures.

Example

fruits = [“apple”, “banana”, “cherry”]

fruits.each { |fruit| puts fruit }

Example Explanation

  • Iterates over the array fruits and outputs each element.
  • Demonstrates Ruby’s powerful iterators for working with collections.

6. Hash

What is a Hash?

Hashes are collections of key-value pairs, similar to dictionaries in other languages.

Syntax

user = {name: “Alice”, age: 25}

Detailed Explanation

  • Created using curly braces ({}).
  • Keys can be symbols, strings, or other data types.
  • Provides fast lookup by keys and is commonly used for configurations, mappings, and structured data.
  • Supports both => syntax and key: value shorthand for symbols.

Example

profile = {name: “Alice”, location: “Wonderland”}

puts “Name: #{profile[:name]}, Location: #{profile[:location]}”

Example Explanation

  • Accesses values using keys.
  • Outputs “Name: Alice, Location: Wonderland”.
  • Illustrates use of symbols as hash keys for brevity and efficiency.

Real-Life Project

Project Name: Data Management System

Project Goal

Develop a system that utilizes various data types to manage and display user information dynamically.

Code for This Project

class User

  def initialize(name, age, hobbies)

    @name = name

    @age = age

    @hobbies = hobbies

  end

 

  def profile

    {

      name: @name,

      age: @age,

      hobbies: @hobbies

    }

  end

 

  def display

    puts “Name: #{@name}”

    puts “Age: #{@age}”

    puts “Hobbies: #{@hobbies.join(‘, ‘)}”

  end

end

 

user = User.new(“Alice”, 30, [“Reading”, “Hiking”])

user.display

puts user.profile

Steps

  1. Create a User class with instance variables for name, age, and hobbies.
  2. Use arrays for hobbies and a hash for the profile representation.
  3. Display and retrieve user data dynamically.

Expected Output

Name: Alice

Age: 30

Hobbies: Reading, Hiking

{:name=>”Alice”, :age=>30, :hobbies=>[“Reading”, “Hiking”]}

Project Explanation

  • Demonstrates the use of strings, arrays, and hashes in a practical scenario.
  • Highlights the combination of data types for structured and readable output.

Insights

Ruby’s data types provide flexibility and expressiveness. Understanding their properties and methods ensures robust and efficient code.

Key Takeaways

  • Use the right data type for the right task.
  • Leverage Ruby’s built-in methods for concise and powerful data manipulation.
  • Avoid unnecessary complexity by mixing data types judiciously.
  • Use symbols for immutable identifiers and arrays/hashes for collections and mappings.

Ruby Variables

This chapter introduces ruby-variables , a foundational concept for storing and manipulating data in programming. Variables in Ruby are dynamically typed and follow conventions that signify their scope and purpose. Understanding variables is essential for writing effective and maintainable Ruby code.

Chapter Goals

  • Understand the purpose of variables in Ruby.
  • Learn about variable types and naming conventions.
  • Explore variable scopes in Ruby.
  • Implement best practices for variable usage in Ruby programs.

Key Characteristics of Ruby Variables

  • Dynamically Typed: Variables can hold any data type, and their type can change at runtime.
  • Flexible Naming: Follow conventions for readability and scope identification.
  • No Declarations: Variables are created upon assignment.
  • Case Sensitivity: Variable names are case-sensitive.
  • Scope-Based: Scope determines variable accessibility.

Basic Rules for Ruby Variables

  • Use descriptive names for clarity and readability.
  • Follow naming conventions based on scope:
    • Local Variables: snake_case starting with a lowercase letter or underscore.
    • Instance Variables: Start with @.
    • Class Variables: Start with @@.
    • Global Variables: Start with $.
  • Avoid reassigning constants, which are conventionally in UPPERCASE.
  • Always initialize variables before use to avoid errors.

Best Practices

  • Use meaningful names that describe the variable’s purpose.
  • Limit the use of global variables for modularity.
  • Leverage instance and class variables appropriately in object-oriented design.
  • Follow community conventions for readability and maintainability.
  • Use constants for values that do not change during execution.

Syntax Table

Serial No Variable Type Syntax/Example Description
1 Local Variable name = “Ruby” Used within a method or block.
2 Instance Variable @name = “Ruby” Belongs to an instance of a class.
3 Class Variable @@counter = 0 Shared among all instances of a class.
4 Global Variable $global = true Accessible from anywhere in the program.
5 Constant PI = 3.14 Value does not change during program execution.

Syntax Explanation

1. Local Variable

What is a Local Variable?

Local variables are used within methods or blocks to store temporary data. They are not accessible outside the scope in which they are defined.

Syntax

name = “Ruby”

Detailed Explanation

  • Declared with a lowercase or underscore prefix.
  • Only accessible within the method or block.
  • Commonly used for intermediate calculations or temporary data storage.
  • Variables can hold any data type, making them highly flexible for diverse tasks such as storing strings, numbers, or arrays.
  • Memory allocated for local variables is released once the scope ends, optimizing performance.

Example

age = 25

puts “Age: #{age}”

Example Explanation

  • Assigns the value 25 to the variable age.
  • Outputs “Age: 25” using string interpolation.
  • Demonstrates simple assignment and output using Ruby syntax.

2. Instance Variable

What is an Instance Variable?

Instance variables belong to an object instance and hold data specific to that instance. They are accessible throughout the class using @ prefix.

Syntax

@name = “Ruby”

Detailed Explanation

  • Starts with @.
  • Available throughout the methods of the class instance.
  • Each object has its own copy of instance variables, making them ideal for storing attributes specific to each instance.
  • Often used in object-oriented programming to encapsulate and manage state within an object.
  • Instance variables are initialized to nil by default if not explicitly set.

Example

class Person

  def initialize(name)

    @name = name

  end

 

  def greet

    “Hello, #{@name}!”

  end

end

 

person = Person.new(“Alice”)

puts person.greet

Example Explanation

  • Initializes the @name variable with the name passed to the Person class.
  • Outputs “Hello, Alice!” using the greet method.
  • Illustrates encapsulation and instance-specific data handling.

3. Class Variable

What is a Class Variable?

Class variables are shared among all instances of a class. They are prefixed with @@.

Syntax

@@counter = 0

Detailed Explanation

  • Declared with @@.
  • Accessible and modifiable by all instances of the class, enabling shared state management.
  • Changes to class variables affect all instances, making them useful for tracking data like counters or shared configurations.
  • Unlike instance variables, class variables are shared and reflect a unified state across all objects.

Example

class Counter

  @@count = 0

 

  def initialize

    @@count += 1

  end

 

  def self.count

    @@count

  end

end

 

Counter.new

Counter.new

puts Counter.count

Example Explanation

  • @@count tracks the number of Counter instances created.
  • Outputs 2 after creating two Counter instances.
  • Demonstrates shared state management using class variables.

4. Global Variable

What is a Global Variable?

Global variables are accessible from anywhere in the program and are prefixed with $. Use them sparingly as they can lead to unexpected side effects.

Syntax

$global = true

Detailed Explanation

  • Declared with $.
  • Accessible globally throughout the program.
  • Suitable for sharing data across unrelated classes and modules but should be used with caution to avoid tight coupling.
  • Overuse of global variables can reduce modularity and increase the risk of conflicts in larger codebases.
  • Global variables remain in memory for the duration of the program, making them resource-intensive if not managed carefully.

Example

$global_var = “I am accessible everywhere”

 

def show_global

  puts $global_var

end

 

show_global

Example Explanation

  • Assigns a string to $global_var.
  • Outputs the string from the show_global method.
  • Demonstrates global accessibility and usage in functions.

5. Constant

What is a Constant?

Constants hold values that do not change during program execution. They are conventionally written in uppercase letters.

Syntax

PI = 3.14

Detailed Explanation

  • Declared with uppercase letters.
  • Can be accessed throughout the program.
  • Reassigning generates a warning but does not throw an error, emphasizing the importance of keeping constant values unchanged.
  • Constants are often used for fixed configuration values, mathematical constants, or reference data.
  • Unlike variables, constants cannot be dynamically assigned within a method.

Example

PI = 3.14

puts “Value of PI: #{PI}”

Example Explanation

  • Assigns 3.14 to the constant PI.
  • Outputs “Value of PI: 3.14”.
  • Demonstrates the use of constants for immutable values.

Real-Life Project

Project Name: Inventory Management System

Project Goal

Develop an inventory management system that uses different types of variables to track inventory and user interactions.

Code for This Project

class Inventory

  @@total_items = 0

 

  def initialize(item_name, quantity)

    @item_name = item_name

    @quantity = quantity

    @@total_items += quantity

  end

 

  def display

    puts “Item: #{@item_name}, Quantity: #{@quantity}”

  end

 

  def self.total_items

    @@total_items

  end

end

 

item1 = Inventory.new(“Apples”, 50)

item2 = Inventory.new(“Oranges”, 30)

 

item1.display

item2.display

 

puts “Total Items: #{Inventory.total_items}”

Steps

  1. Define a class Inventory with an instance variable @item_name and @quantity.
  2. Use a class variable @@total_items to track the total quantity of items.
  3. Create methods to display item details and total items.

Expected Output

Item: Apples, Quantity: 50

Item: Oranges, Quantity: 30

Total Items: 80

Project Explanation

  • Demonstrates the use of local, instance, and class variables.
  • Tracks individual items and total inventory effectively.

Insights

Ruby variables offer flexibility and ease of use. Understanding their scope and conventions ensures effective and maintainable code.

Key Takeaways

  • Follow Ruby naming conventions for clarity.
  • Use variable types appropriately based on scope and purpose.
  • Limit the use of global variables to avoid tightly coupled code.
  • Leverage instance and class variables in object-oriented programming.