From 142d9f81067406d214efe263883c1d973d6f733d Mon Sep 17 00:00:00 2001 From: Sivaprasath <121082414+sivaprasath2004@users.noreply.github.com> Date: Thu, 25 Jul 2024 10:08:26 +0530 Subject: [PATCH] Added Ruby --- courses/Ruby/Overview.md | 77 ++++++ courses/Ruby/_category_.json | 8 + .../Advance-File-Handling/_category_.json | 8 + .../Advance-File-Handling/large-Files.md | 57 +++++ .../Advance-File-Handling/memory-mapped.md | 79 ++++++ .../Advanced-metaprogramming/DSLs.md | 92 +++++++ .../Advanced-metaprogramming/Singleton.md | 86 +++++++ .../Advanced-metaprogramming/_category_.json | 8 + .../Concurrency and Parallelism/Intro.md | 91 +++++++ .../_category_.json | 8 + .../synchronization.md | 86 +++++++ .../Network-programming/_category_.json | 8 + .../Network-programming/client-server.md | 111 +++++++++ .../Network-programming/into.md | 48 ++++ .../Ruby on Rails/Introduction.md | 36 +++ .../Ruby on Rails/_category_.json | 8 + .../Ruby/advanced-level/Ruby on Rails/mvc.md | 97 ++++++++ courses/Ruby/advanced-level/_category_.json | 8 + .../Arrays and Hashes/Arrays.md | 45 ++++ .../Arrays and Hashes/_category_.json | 8 + .../Arrays and Hashes/hashes.md | 94 +++++++ .../Basic-syntax/Basic-syntax.md | 90 +++++++ .../Basic-syntax/_category_.json | 8 + .../beginner-level/Basic-syntax/constants.md | 77 ++++++ .../beginner-level/Control-Strucutre/Loops.md | 214 ++++++++++++++++ .../Control-Strucutre/_category_.json | 8 + .../Control-Strucutre/statements.md | 79 ++++++ .../Function-and-methods/Category_.json | 8 + .../Function-and-methods/arguments.md | 90 +++++++ .../Function-and-methods/define-methods.md | 33 +++ .../Introduction/_category_.json | 8 + .../Ruby/beginner-level/Introduction/setup.md | 58 +++++ .../Introduction/what-is-ruby.md | 24 ++ .../beginner-level/Strings/_category_.json | 8 + .../Ruby/beginner-level/Strings/concepts.md | 133 ++++++++++ courses/Ruby/beginner-level/_category_.json | 8 + .../Enumerables-and-Iteration/_category_.json | 8 + .../custom-iterations.md | 59 +++++ .../working-with-Enumerables.md | 84 +++++++ .../Gems-and-builder/_category_.json | 8 + .../Gems-and-builder/intro.md | 49 ++++ .../Gems-and-builder/publishing.md | 92 +++++++ .../intermediate-level/OOPS/_category_.json | 8 + .../Ruby/intermediate-level/OOPS/concepts.md | 231 ++++++++++++++++++ .../Ruby/intermediate-level/_category_.json | 8 + .../metaprogramming/Dynamic-method.md | 68 ++++++ .../metaprogramming/_category_.json | 8 + .../metaprogramming/intro.md | 54 ++++ .../working-with-API/JSON-and-XML.md | 100 ++++++++ .../working-with-API/_category_.json | 8 + .../working-with-API/http.md | 60 +++++ 51 files changed, 2754 insertions(+) create mode 100644 courses/Ruby/Overview.md create mode 100644 courses/Ruby/_category_.json create mode 100644 courses/Ruby/advanced-level/Advance-File-Handling/_category_.json create mode 100644 courses/Ruby/advanced-level/Advance-File-Handling/large-Files.md create mode 100644 courses/Ruby/advanced-level/Advance-File-Handling/memory-mapped.md create mode 100644 courses/Ruby/advanced-level/Advanced-metaprogramming/DSLs.md create mode 100644 courses/Ruby/advanced-level/Advanced-metaprogramming/Singleton.md create mode 100644 courses/Ruby/advanced-level/Advanced-metaprogramming/_category_.json create mode 100644 courses/Ruby/advanced-level/Concurrency and Parallelism/Intro.md create mode 100644 courses/Ruby/advanced-level/Concurrency and Parallelism/_category_.json create mode 100644 courses/Ruby/advanced-level/Concurrency and Parallelism/synchronization.md create mode 100644 courses/Ruby/advanced-level/Network-programming/_category_.json create mode 100644 courses/Ruby/advanced-level/Network-programming/client-server.md create mode 100644 courses/Ruby/advanced-level/Network-programming/into.md create mode 100644 courses/Ruby/advanced-level/Ruby on Rails/Introduction.md create mode 100644 courses/Ruby/advanced-level/Ruby on Rails/_category_.json create mode 100644 courses/Ruby/advanced-level/Ruby on Rails/mvc.md create mode 100644 courses/Ruby/advanced-level/_category_.json create mode 100644 courses/Ruby/beginner-level/Arrays and Hashes/Arrays.md create mode 100644 courses/Ruby/beginner-level/Arrays and Hashes/_category_.json create mode 100644 courses/Ruby/beginner-level/Arrays and Hashes/hashes.md create mode 100644 courses/Ruby/beginner-level/Basic-syntax/Basic-syntax.md create mode 100644 courses/Ruby/beginner-level/Basic-syntax/_category_.json create mode 100644 courses/Ruby/beginner-level/Basic-syntax/constants.md create mode 100644 courses/Ruby/beginner-level/Control-Strucutre/Loops.md create mode 100644 courses/Ruby/beginner-level/Control-Strucutre/_category_.json create mode 100644 courses/Ruby/beginner-level/Control-Strucutre/statements.md create mode 100644 courses/Ruby/beginner-level/Function-and-methods/Category_.json create mode 100644 courses/Ruby/beginner-level/Function-and-methods/arguments.md create mode 100644 courses/Ruby/beginner-level/Function-and-methods/define-methods.md create mode 100644 courses/Ruby/beginner-level/Introduction/_category_.json create mode 100644 courses/Ruby/beginner-level/Introduction/setup.md create mode 100644 courses/Ruby/beginner-level/Introduction/what-is-ruby.md create mode 100644 courses/Ruby/beginner-level/Strings/_category_.json create mode 100644 courses/Ruby/beginner-level/Strings/concepts.md create mode 100644 courses/Ruby/beginner-level/_category_.json create mode 100644 courses/Ruby/intermediate-level/Enumerables-and-Iteration/_category_.json create mode 100644 courses/Ruby/intermediate-level/Enumerables-and-Iteration/custom-iterations.md create mode 100644 courses/Ruby/intermediate-level/Enumerables-and-Iteration/working-with-Enumerables.md create mode 100644 courses/Ruby/intermediate-level/Gems-and-builder/_category_.json create mode 100644 courses/Ruby/intermediate-level/Gems-and-builder/intro.md create mode 100644 courses/Ruby/intermediate-level/Gems-and-builder/publishing.md create mode 100644 courses/Ruby/intermediate-level/OOPS/_category_.json create mode 100644 courses/Ruby/intermediate-level/OOPS/concepts.md create mode 100644 courses/Ruby/intermediate-level/_category_.json create mode 100644 courses/Ruby/intermediate-level/metaprogramming/Dynamic-method.md create mode 100644 courses/Ruby/intermediate-level/metaprogramming/_category_.json create mode 100644 courses/Ruby/intermediate-level/metaprogramming/intro.md create mode 100644 courses/Ruby/intermediate-level/working-with-API/JSON-and-XML.md create mode 100644 courses/Ruby/intermediate-level/working-with-API/_category_.json create mode 100644 courses/Ruby/intermediate-level/working-with-API/http.md diff --git a/courses/Ruby/Overview.md b/courses/Ruby/Overview.md new file mode 100644 index 000000000..cc4995120 --- /dev/null +++ b/courses/Ruby/Overview.md @@ -0,0 +1,77 @@ +--- +title: Ruby Course Outline +sidebar_label: Course Overview +sidebar_position: 1 +description: Ruby Course Outline. +tags: [courses,Ruby,Overview] +--- + + +#### Beginner Level + +**1. Introduction to Ruby** + - What is Ruby & History + - Setting up the development environment + +**2. Basic Syntax and Structure** + - Ruby syntax basics + - Input and output operations + +**3. Control Structures** + - Conditional statements (if, unless, case-when) + - Loops (while, until, for, each) + +**4. Functions and Methods** + - Defining methods + - Method arguments and return values + +**5. Arrays and Hashes** + - Arrays + - Hashes + +**6. Strings** + - String concept + +#### Intermediate Level + +**1. Advanced OOP Concepts** + - OOPS Overall View + +**2. Enumerables and Iterators** + - Enumerables + - Custom iterators with Enumerator + +**3. Metaprogramming** + - Introduction to metaprogramming + - Defining methods dynamically + +**4. Gems and Bundler** + - Introduction & uses + - Creating and publishing your own gem + +**5. Working with APIs** + - Dynamic Method + - Parsing JSON and XML + +#### Advanced Level + +**1. Advanced Metaprogramming** + - Intro & Concepts + - Defining DSLs (Domain-Specific Languages) + +**2. Concurrency and Parallelism** + - Concurrency and Parallelism + - Synchronization techniques + +**3. Network Programming** + - Introduction to network programming + - Building simple client-server applications + +**4. Advanced File Handling** + - Introduction + - Using memory-mapped files + +**5. Ruby on Rails** + - Introduction to Ruby on Rails + - MVC architecture in Rails + \ No newline at end of file diff --git a/courses/Ruby/_category_.json b/courses/Ruby/_category_.json new file mode 100644 index 000000000..80a6e0e56 --- /dev/null +++ b/courses/Ruby/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Ruby", + "position": 16, + "link": { + "type": "generated-index", + "description": "Learn Ruby programming Language." + } + } \ No newline at end of file diff --git a/courses/Ruby/advanced-level/Advance-File-Handling/_category_.json b/courses/Ruby/advanced-level/Advance-File-Handling/_category_.json new file mode 100644 index 000000000..97fc120bf --- /dev/null +++ b/courses/Ruby/advanced-level/Advance-File-Handling/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Advanced File Handling", + "position": 4, + "link": { + "type": "generated-index", + "description": "Learn Advanced File Handling in Ruby." + } + } \ No newline at end of file diff --git a/courses/Ruby/advanced-level/Advance-File-Handling/large-Files.md b/courses/Ruby/advanced-level/Advance-File-Handling/large-Files.md new file mode 100644 index 000000000..d3412f46b --- /dev/null +++ b/courses/Ruby/advanced-level/Advance-File-Handling/large-Files.md @@ -0,0 +1,57 @@ +--- +id: lesson-1 +title: "Advanced File Handling in Ruby" +sidebar_label: Introduction +sidebar_position: 1 +description: "Advanced File Handling in Ruby" +tags: [courses,Advance-level,Introduction] +--- + +Advanced file handling involves techniques for working efficiently with files, particularly when dealing with large files or when needing to perform high-performance I/O operations. + +#### **1. Working with Large Files** + +When dealing with large files, it's crucial to process the file in chunks rather than loading the entire file into memory. This approach helps manage memory usage and improves performance. + +**Example**: Reading a Large File Line by Line + +```ruby +File.open('large_file.txt', 'r') do |file| + while line = file.gets + # Process each line + puts line + end +end +``` + +**Example**: Writing to a Large File in Chunks + +```ruby +File.open('large_file_output.txt', 'w') do |file| + (1..1000000).each do |i| + file.write("Line #{i}\n") + end +end +``` + +#### **2. File Locking Mechanisms** + +File locking is used to prevent multiple processes from accessing a file simultaneously, which can lead to data corruption. Ruby does not have built-in file locking, but you can use system calls or libraries for this purpose. + +**Example**: File Locking with `flock` + +```ruby +require 'fcntl' + +file = File.open('lockfile.txt', 'r+') +file.flock(File::LOCK_EX) # Exclusive lock + +# Perform file operations +file.write("Some important data") + +file.flock(File::LOCK_UN) # Unlock the file +file.close +``` +:::note +`flock` is used for advisory locking, which means it's up to cooperating processes to respect the locks. +::: \ No newline at end of file diff --git a/courses/Ruby/advanced-level/Advance-File-Handling/memory-mapped.md b/courses/Ruby/advanced-level/Advance-File-Handling/memory-mapped.md new file mode 100644 index 000000000..6c1b60b54 --- /dev/null +++ b/courses/Ruby/advanced-level/Advance-File-Handling/memory-mapped.md @@ -0,0 +1,79 @@ +--- +id: lesson-2 +title: "Using Memory-Mapped Files" +sidebar_label: Memory-Mapped Files +sidebar_position: 2 +description: "Using Memory-Mapped Files" +tags: [courses,Advance-level,Introduction] +--- + + +Memory-mapped files allow a file to be mapped into the memory space of a process. This approach can be efficient for large files and can provide a way to access file contents as if they were in memory. + +**Example**: Memory-Mapped Files with `mmap` + +```ruby +require 'mmap' + +File.open('large_file.txt', 'r') do |file| + length = file.size + map = Mmap.new(file.fileno, length, Mmap::ACCESS_READ) + + # Access the mapped file + puts map[0..100] # Read the first 100 bytes + + map.close +end +``` + +**Note**: The `mmap` gem provides memory-mapped file capabilities. Install it via `gem install mmap`. + +#### **File I/O Performance Optimization** + +To optimize file I/O performance, consider using buffering and minimizing the number of I/O operations. + +**Example**: Buffered Writing + +```ruby +File.open('buffered_output.txt', 'w') do |file| + file.sync = false # Disable auto-flushing + + (1..1000000).each do |i| + file.write("Line #{i}\n") + file.flush if i % 1000 == 0 # Manually flush buffer periodically + end +end +``` + +**Example**: Using `IO#readpartial` for Efficient Reading + +```ruby +File.open('large_file.txt', 'r') do |file| + buffer = "" + while file.readpartial(1024, buffer) + # Process the buffer + puts buffer + buffer.clear + end +end +``` + +:::tip +1. **Avoid Reading Entire Files into Memory**: + - For large files, process data in chunks to avoid high memory usage. + +2. **Implement Proper File Locking**: + - Use file locking mechanisms to prevent concurrent access issues, especially in multi-process applications. + +3. **Optimize I/O Operations**: + - Use buffering to reduce the number of I/O operations and improve performance. Consider memory-mapped files for large datasets. + +4. **Efficient File Processing**: + - Process large files efficiently by reading and writing in chunks. Avoid loading entire files into memory. + +5. **File Locking**: + - Use file locking to prevent data corruption in concurrent file access scenarios. + +6. **Performance Optimization**: + - Optimize file I/O operations by using techniques such as buffering and memory-mapped files for better performance. +::: \ No newline at end of file diff --git a/courses/Ruby/advanced-level/Advanced-metaprogramming/DSLs.md b/courses/Ruby/advanced-level/Advanced-metaprogramming/DSLs.md new file mode 100644 index 000000000..788cc4a15 --- /dev/null +++ b/courses/Ruby/advanced-level/Advanced-metaprogramming/DSLs.md @@ -0,0 +1,92 @@ +--- +id: lesson-2 +title: "Defining DSLs (Domain-Specific Languages)" +sidebar_label: DSLs +sidebar_position: 2 +description: "Defining DSLs (Domain-Specific Languages)" +tags: [courses,Advance-level,Introduction] +--- + + +- DSLs are specialized languages tailored to a particular domain. Ruby's flexible syntax makes it easy to define DSLs. + + **Example**: + ```ruby + class HtmlBuilder + def initialize + @html = "" + end + + def method_missing(tag, content = nil, &block) + @html << "<#{tag}>" + @html << content.to_s + @html << block.call if block_given? + @html << "" + end + + def result + @html + end + end + + builder = HtmlBuilder.new + builder.html do + builder.body do + builder.h1 "Hello World" + builder.p "This is a paragraph." + end + end + + puts builder.result + ``` + + **Output**: + ```html +

Hello World

This is a paragraph.

+ ``` + +#### Advanced Use of Hooks and Callbacks + +- Ruby provides hooks and callbacks that can be used to run code at certain points in an object's lifecycle. + + **Example**: + ```ruby + class MyClass + def initialize + puts "Initializing..." + end + + def self.inherited(subclass) + puts "#{subclass} has been inherited" + end + end + + class SubClass < MyClass + end + ``` + + **Output**: + ```bash + Initializing... + SubClass has been inherited + ``` + +:::tip +1. **Singleton Methods**: + - Useful for defining methods on individual instances rather than classes. Ideal for adding custom behavior to specific objects. + +2. **Dynamic Evaluation**: + - `class_eval` and `instance_eval` allow dynamic changes to classes and objects. Use them for meta-level programming tasks. + +3. **Domain-Specific Languages (DSLs)**: + - Ruby’s syntax makes it easy to create DSLs. Leverage this to create expressive, domain-specific interfaces. + +4. **Understand Performance Implications**: + - Metaprogramming can impact performance. Use it judiciously and profile if necessary. + +5. **Maintain Readability**: + - Advanced metaprogramming can make code harder to understand. Ensure that your code remains readable and maintainable. + +6. **Use Metaprogramming for Reusability**: + - Apply metaprogramming techniques to reduce code duplication and increase flexibility. +::: \ No newline at end of file diff --git a/courses/Ruby/advanced-level/Advanced-metaprogramming/Singleton.md b/courses/Ruby/advanced-level/Advanced-metaprogramming/Singleton.md new file mode 100644 index 000000000..f6cfb4654 --- /dev/null +++ b/courses/Ruby/advanced-level/Advanced-metaprogramming/Singleton.md @@ -0,0 +1,86 @@ +--- +id: lesson-1 +title: "Advanced Metaprogramming in Ruby" +sidebar_label: Intro & Concepts +sidebar_position: 1 +description: "Learn Advanced Metaprogramming in Ruby" +tags: [courses,Advance-level,Introduction] +--- + +Metaprogramming in Ruby allows you to write code that can modify or extend itself at runtime. This powerful feature can be used for various advanced programming techniques, such as creating domain-specific languages (DSLs) or dynamically altering classes. + +#### **1. Singleton Methods and Classes** + +**Singleton Methods**: +- Singleton methods are methods that are defined on a single object rather than on the class of the object. + + **Example**: + ```ruby + obj = "I am a string" + + # Define a singleton method on obj + def obj.singleton_method + "I am a singleton method" + end + + puts obj.singleton_method # Output: I am a singleton method + ``` + +**Singleton Classes**: +- Singleton classes are special classes associated with a single object. They allow you to define methods that only affect that particular object. + + **Example**: + ```ruby + obj = "I am a string" + + class << obj + def singleton_method + "This is a singleton class method" + end + end + + puts obj.singleton_method # Output: This is a singleton class method + ``` + +#### **2. Using `class_eval` and `instance_eval`** + +**`class_eval`**: +- `class_eval` is used to evaluate a string or block within the context of a class, allowing you to modify the class dynamically. + + **Example**: + ```ruby + class MyClass + def greet + "Hello" + end + end + + MyClass.class_eval do + def farewell + "Goodbye" + end + end + + obj = MyClass.new + puts obj.greet # Output: Hello + puts obj.farewell # Output: Goodbye + ``` + +**`instance_eval`**: +- `instance_eval` is used to evaluate a string or block within the context of a specific object, allowing you to modify the object dynamically. + + **Example**: + ```ruby + class MyClass + def initialize + @name = "Initial Name" + end + end + + obj = MyClass.new + obj.instance_eval do + @name = "Changed Name" + end + + puts obj.instance_variable_get(:@name) # Output: Changed Name + ``` diff --git a/courses/Ruby/advanced-level/Advanced-metaprogramming/_category_.json b/courses/Ruby/advanced-level/Advanced-metaprogramming/_category_.json new file mode 100644 index 000000000..eb1bad414 --- /dev/null +++ b/courses/Ruby/advanced-level/Advanced-metaprogramming/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Advanced Metaprogramming", + "position": 1, + "link": { + "type": "generated-index", + "description": "Learn Advanced Metaprogramming in Ruby." + } + } \ No newline at end of file diff --git a/courses/Ruby/advanced-level/Concurrency and Parallelism/Intro.md b/courses/Ruby/advanced-level/Concurrency and Parallelism/Intro.md new file mode 100644 index 000000000..1ecfd987c --- /dev/null +++ b/courses/Ruby/advanced-level/Concurrency and Parallelism/Intro.md @@ -0,0 +1,91 @@ +--- +id: lesson-1 +title: "Concurrency and Parallelism in Ruby" +sidebar_label: Concurrency and Parallelism +sidebar_position: 1 +description: "Concurrency and Parallelism in Ruby" +tags: [courses,Advance-level,Introduction] +--- + + +Concurrency and parallelism are essential for writing efficient and responsive programs. In Ruby, these concepts are supported through threading, fibers, and various libraries. + +#### **1. Introduction to Threading and Fibers** + +**Threading**: +- Threads allow multiple tasks to run concurrently within a single process. Ruby’s `Thread` class provides basic support for multithreading. + +**Fibers**: +- Fibers are lightweight concurrency primitives used for cooperative multitasking. Unlike threads, fibers voluntarily yield control to other fibers. + +**Example**: +```ruby +# Example of Threading +thread1 = Thread.new do + 5.times do |i| + puts "Thread 1: #{i}" + sleep 1 + end +end + +thread2 = Thread.new do + 5.times do |i| + puts "Thread 2: #{i}" + sleep 1 + end +end + +thread1.join +thread2.join +``` + +**Output**: +```bash +Thread 1: 0 +Thread 2: 0 +Thread 1: 1 +Thread 2: 1 +Thread 1: 2 +Thread 2: 2 +Thread 1: 3 +Thread 2: 3 +Thread 1: 4 +Thread 2: 4 +``` + +#### **2. Creating and Managing Threads** + +**Creating Threads**: +- Threads are created using `Thread.new`. Each thread runs a block of code concurrently. + +**Managing Threads**: +- Use `Thread#join` to wait for a thread to finish execution. `Thread#kill` can terminate a thread. + +**Example**: +```ruby +threads = [] + +5.times do |i| + threads << Thread.new do + puts "Thread #{i} is running" + sleep rand(1..3) + puts "Thread #{i} is done" + end +end + +threads.each(&:join) +``` + +**Output**: +```bash +Thread 0 is running +Thread 1 is running +Thread 2 is running +Thread 3 is running +Thread 4 is running +Thread 0 is done +Thread 1 is done +Thread 2 is done +Thread 3 is done +Thread 4 is done +``` \ No newline at end of file diff --git a/courses/Ruby/advanced-level/Concurrency and Parallelism/_category_.json b/courses/Ruby/advanced-level/Concurrency and Parallelism/_category_.json new file mode 100644 index 000000000..199f0b18b --- /dev/null +++ b/courses/Ruby/advanced-level/Concurrency and Parallelism/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Concurrency and Parallelism", + "position": 2, + "link": { + "type": "generated-index", + "description": "Learn Concurrency and Parallelism in Ruby." + } + } \ No newline at end of file diff --git a/courses/Ruby/advanced-level/Concurrency and Parallelism/synchronization.md b/courses/Ruby/advanced-level/Concurrency and Parallelism/synchronization.md new file mode 100644 index 000000000..2507bc9c4 --- /dev/null +++ b/courses/Ruby/advanced-level/Concurrency and Parallelism/synchronization.md @@ -0,0 +1,86 @@ +--- +id: lesson-2 +title: "Synchronization Techniques" +sidebar_label: Synchronization Techniques +sidebar_position: 2 +description: "Synchronization Techniques in Ruby" +tags: [courses,Advance-level,Introduction] +--- + +**Mutex**: +- A Mutex (short for mutual exclusion) is used to synchronize access to shared resources. + +**Example**: +```ruby +require 'thread' + +mutex = Mutex.new +shared_resource = 0 + +threads = [] +10.times do |i| + threads << Thread.new do + 100.times do + mutex.synchronize do + shared_resource += 1 + end + end + end +end + +threads.each(&:join) +puts "Final value of shared_resource: #{shared_resource}" +``` + +**Output**: +```bash +Final value of shared_resource: 1000 +``` + +#### Using `concurrent-ruby` for Advanced Concurrency + +**concurrent-ruby**: +- The `concurrent-ruby` gem provides advanced concurrency abstractions like futures, promises, and thread pools. + +**Example**: +```ruby +require 'concurrent-ruby' + +future = Concurrent::Future.new do + sleep 2 + "Result from future" +end + +# Do other work here +puts "Waiting for future..." + +# Get result from future +puts future.value # Blocks until the future completes +``` + +**Output**: +```bash +Waiting for future... +Result from future +``` + +:::tip + +1. **Avoid Shared State**: + - Minimize shared state between threads to reduce the complexity of synchronization and avoid race conditions. + +2. **Use Synchronization Mechanisms Wisely**: + - Use mutexes and other synchronization tools to manage access to shared resources, but avoid overusing them as they can lead to bottlenecks. + +3. **Profile and Test Concurrent Code**: + - Concurrency issues can be subtle. Profile and test your concurrent code thoroughly to ensure it behaves as expected. + +4. **Threads and Fibers**: + - Threads allow parallel execution within a process. Fibers are more lightweight but require cooperative multitasking. + +5. **Synchronization**: + - Proper synchronization is crucial for preventing race conditions and ensuring data integrity when using multiple threads. + +6. **Advanced Concurrency Tools**: + - `concurrent-ruby` provides powerful abstractions for managing concurrency, such as futures and thread pools, which can simplify complex concurrency tasks. +::: \ No newline at end of file diff --git a/courses/Ruby/advanced-level/Network-programming/_category_.json b/courses/Ruby/advanced-level/Network-programming/_category_.json new file mode 100644 index 000000000..0a63dc609 --- /dev/null +++ b/courses/Ruby/advanced-level/Network-programming/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Network Programming", + "position": 3, + "link": { + "type": "generated-index", + "description": "Learn Network Programming in Ruby." + } + } \ No newline at end of file diff --git a/courses/Ruby/advanced-level/Network-programming/client-server.md b/courses/Ruby/advanced-level/Network-programming/client-server.md new file mode 100644 index 000000000..e308976ff --- /dev/null +++ b/courses/Ruby/advanced-level/Network-programming/client-server.md @@ -0,0 +1,111 @@ +--- +id: lesson-2 +title: "Building Simple Client-Server Applications" +sidebar_label: Client-Server +sidebar_position: 2 +description: "Building Simple Client-Server Applications" +tags: [courses,Advance-level,Introduction] +--- + +In a client-server model, the server listens for incoming connections and handles requests, while the client connects to the server and sends requests. + +**Example**: Basic HTTP Server + +**HTTP Server**: +```ruby +require 'socket' + +server = TCPServer.new(8080) + +loop do + client = server.accept + request = client.gets + puts request + client.puts "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nHello World" + client.close +end +``` + +**HTTP Client**: +```ruby +require 'socket' + +client = TCPSocket.new('localhost', 8080) +client.puts "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n" +response = client.read +puts response +client.close +``` + +**Output for HTTP Client**: +```bash +HTTP/1.1 200 OK +Content-Type: text/plain + +Hello World +``` + +#### Understanding TCP/IP and UDP Protocols + +**TCP (Transmission Control Protocol)**: +- Connection-oriented protocol. +- Ensures data is reliably delivered in order. +- Provides flow control and error recovery. + +**UDP (User Datagram Protocol)**: +- Connectionless protocol. +- Does not guarantee delivery, order, or error recovery. +- Used for applications that need faster communication and can handle occasional data loss. + +**Example**: Basic UDP Client and Server + +**UDP Server**: +```ruby +require 'socket' + +server = UDPSocket.new +server.bind('localhost', 2000) + +loop do + message, sender = server.recvfrom(1024) + puts "Received message: #{message}" + server.send("Message received", 0, sender[3], sender[1]) +end +``` + +**UDP Client**: +```ruby +require 'socket' + +client = UDPSocket.new +client.send("Hello UDP Server", 0, 'localhost', 2000) +response, _ = client.recvfrom(1024) +puts response +client.close +``` + +**Output for UDP Client**: +```bash +Message received +``` + +:::tip + +1. **Handle Exceptions Gracefully**: + - Network programming involves many potential points of failure, such as network issues or connection timeouts. Always handle exceptions to prevent your application from crashing. + +2. **Use Asynchronous I/O for Better Performance**: + - For applications that need to handle many simultaneous connections, consider using asynchronous I/O to improve performance. + +3. **Secure Network Communication**: + - For sensitive data, use secure protocols (e.g., TLS/SSL) and validate input to protect against attacks such as injection and man-in-the-middle. + +4. **Socket Types**: + - Understand the difference between TCP (reliable, connection-oriented) and UDP (unreliable, connectionless) sockets to choose the right protocol for your application. + +5. **Client-Server Model**: + - In network programming, clearly define the roles and responsibilities of the client and server. Ensure proper handling of requests and responses. + +6. **Error Handling**: + - Network programming is prone to various errors due to network instability or incorrect configurations. Implement robust error handling to manage these issues effectively. +::: \ No newline at end of file diff --git a/courses/Ruby/advanced-level/Network-programming/into.md b/courses/Ruby/advanced-level/Network-programming/into.md new file mode 100644 index 000000000..9fdc6a246 --- /dev/null +++ b/courses/Ruby/advanced-level/Network-programming/into.md @@ -0,0 +1,48 @@ +--- +id: lesson-1 +title: "Network Programming in Ruby" +sidebar_label: Intro to Network Programming +sidebar_position: 1 +description: "Network Programming in Ruby" +tags: [courses,Advance-level,Introduction] +--- + + +Network programming involves writing software that communicates over a network, typically using protocols like TCP/IP and UDP. Ruby provides libraries and classes to facilitate network communication. + +#### **1. Introduction to Network Programming** + +Network programming in Ruby generally involves working with sockets, which allow for communication between processes over a network. Ruby's standard library includes `Socket`, which provides fundamental networking functionalities. + +#### **2. Working with Sockets** + +**Sockets** are endpoints for sending and receiving data across a network. Ruby's `Socket` library allows you to create and use sockets for network communication. + +**Example**: Basic TCP Client and Server + +**TCP Server**: +```ruby +require 'socket' + +server = TCPServer.new('localhost', 2000) # Create a server listening on port 2000 + +loop do + client = server.accept # Wait for a client to connect + client.puts "Hello from server!" # Send a message to the client + client.close # Close the connection +end +``` + +**TCP Client**: +```ruby +require 'socket' + +client = TCPSocket.new('localhost', 2000) # Connect to the server +puts client.gets # Read the response from the server +client.close # Close the connection +``` + +**Output for TCP Client**: +```bash +Hello from server! +``` diff --git a/courses/Ruby/advanced-level/Ruby on Rails/Introduction.md b/courses/Ruby/advanced-level/Ruby on Rails/Introduction.md new file mode 100644 index 000000000..ef8eacae1 --- /dev/null +++ b/courses/Ruby/advanced-level/Ruby on Rails/Introduction.md @@ -0,0 +1,36 @@ +--- +id: lesson-1 +title: "Ruby on Rails" +sidebar_label: Introduction +sidebar_position: 1 +description: "Learn Ruby on Rails" +tags: [courses,Advance-level,Introduction] +--- + + +Ruby on Rails, often just called Rails, is a web application framework written in Ruby. It follows the model-view-controller (MVC) architectural pattern and emphasizes the use of convention over configuration (CoC) and the don't repeat yourself (DRY) principle. + +#### **1. Introduction to Ruby on Rails** + +**Ruby on Rails** is designed to make web application development faster and easier by providing a comprehensive set of tools and libraries. It encourages the use of best practices and common patterns. + +**Features of Ruby on Rails**: +- **Convention over Configuration**: Rails has sensible defaults that allow developers to focus on writing code instead of configuring settings. +- **DRY Principle**: Rails encourages reusable code to avoid redundancy. +- **Built-in Testing Framework**: Rails includes tools for testing, making it easier to write and maintain testable code. + +#### **2. Setting up a Rails Project** + +To set up a Rails project, you need to have Ruby and Rails installed on your system. You can install Rails using the following command: + +```bash +gem install rails +``` + +**Creating a New Rails Project**: +```bash +rails new myapp +cd myapp +``` + +This command generates a new Rails application with a default directory structure and configuration. \ No newline at end of file diff --git a/courses/Ruby/advanced-level/Ruby on Rails/_category_.json b/courses/Ruby/advanced-level/Ruby on Rails/_category_.json new file mode 100644 index 000000000..f57239148 --- /dev/null +++ b/courses/Ruby/advanced-level/Ruby on Rails/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Ruby on Rails", + "position": 5, + "link": { + "type": "generated-index", + "description": "Learn Ruby on Rails." + } + } \ No newline at end of file diff --git a/courses/Ruby/advanced-level/Ruby on Rails/mvc.md b/courses/Ruby/advanced-level/Ruby on Rails/mvc.md new file mode 100644 index 000000000..684d142ef --- /dev/null +++ b/courses/Ruby/advanced-level/Ruby on Rails/mvc.md @@ -0,0 +1,97 @@ +--- +id: lesson-2 +title: "MVC Architecture in Rails" +sidebar_label: MVC +sidebar_position: 2 +description: "MVC Architecture in Rails" +tags: [courses,Advance-level,Introduction] +--- + + +Rails follows the MVC architecture, which divides an application into three interconnected components: + +- **Model**: Represents the data and the business logic. Interacts with the database. +- **View**: Handles the display of data. It renders the user interface. +- **Controller**: Manages the flow of data between the Model and the View. It processes user input and updates the Model and View accordingly. + +**Example**: +- **Model**: `app/models/user.rb` + ```ruby + class User < ApplicationRecord + validates :name, presence: true + end + ``` +- **Controller**: `app/controllers/users_controller.rb` + ```ruby + class UsersController < ApplicationController + def index + @users = User.all + end + + def show + @user = User.find(params[:id]) + end + + def new + @user = User.new + end + + def create + @user = User.new(user_params) + if @user.save + redirect_to @user + else + render 'new' + end + end + + private + + def user_params + params.require(:user).permit(:name) + end + end + ``` +- **View**: `app/views/users/index.html.erb` + ```erb +

Users

+ + ``` + +#### Building a Simple Rails Application + +To build a simple Rails application, follow these steps: + +**Step 1: Generate a Resource**: +```bash +rails generate scaffold User name:string +``` +This command generates a model, controller, views, and routes for the `User` resource. + +**Step 2: Migrate the Database**: +```bash +rails db:migrate +``` +This command runs the generated migration to create the `users` table in the database. + +**Step 3: Start the Rails Server**: +```bash +rails server +``` +The Rails server will start, and you can access your application at `http://localhost:3000`. + +**Step 4: Access the Users Resource**: +Open your browser and go to `http://localhost:3000/users`. You can create, read, update, and delete users. + +:::tip +1. **Understand the MVC Pattern**: Familiarize yourself with the MVC architecture as it's fundamental to Rails applications. +2. **Leverage Rails Generators**: Use Rails generators to quickly create models, controllers, views, and other components. +3. **Read the Rails Guides**: The official Rails Guides are a comprehensive resource for learning Rails and are constantly updated. +4. **Convention over Configuration**: Rails has many sensible defaults that minimize the need for configuration. +5. **MVC Architecture**: Rails applications are organized using the MVC pattern, promoting a clear separation of concerns. +6. **Built-in Tools and Libraries**: Rails provides a wide array of built-in tools and libraries to speed up development and enforce best practices. +::: \ No newline at end of file diff --git a/courses/Ruby/advanced-level/_category_.json b/courses/Ruby/advanced-level/_category_.json new file mode 100644 index 000000000..1db78030c --- /dev/null +++ b/courses/Ruby/advanced-level/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Advanced Level", + "position": 4, + "link": { + "type": "generated-index", + "description": "Learn Ruby Advanced Concept." + } + } \ No newline at end of file diff --git a/courses/Ruby/beginner-level/Arrays and Hashes/Arrays.md b/courses/Ruby/beginner-level/Arrays and Hashes/Arrays.md new file mode 100644 index 000000000..68fb73e73 --- /dev/null +++ b/courses/Ruby/beginner-level/Arrays and Hashes/Arrays.md @@ -0,0 +1,45 @@ +--- +id: lesson-1 +title: "Introduction to Arrays" +sidebar_label: Arrays +sidebar_position: 1 +description: "Introduction to Arrays" +tags: [courses,beginner-level,Ruby,Introduction] +--- + +Arrays in Ruby are ordered, integer-indexed collections of objects. They can hold objects of any type. + +```ruby +# Creating an array +numbers = [1, 2, 3, 4, 5] + +# Accessing elements +puts numbers[0] # Output: 1 + +# Modifying elements +numbers[2] = 99 +puts numbers.inspect # Output: [1, 2, 99, 4, 5] +``` + +#### Array Methods and Operations +Ruby provides a rich set of methods to manipulate arrays. + +```ruby +# Adding elements +numbers.push(6) +numbers << 7 +puts numbers.inspect # Output: [1, 2, 99, 4, 5, 6, 7] + +# Removing elements +numbers.pop +puts numbers.inspect # Output: [1, 2, 99, 4, 5, 6] + +# Iterating over elements +numbers.each do |num| + puts num +end + +# Selecting elements +even_numbers = numbers.select { |num| num.even? } +puts even_numbers.inspect # Output: [2, 4, 6] +``` \ No newline at end of file diff --git a/courses/Ruby/beginner-level/Arrays and Hashes/_category_.json b/courses/Ruby/beginner-level/Arrays and Hashes/_category_.json new file mode 100644 index 000000000..2cb43264b --- /dev/null +++ b/courses/Ruby/beginner-level/Arrays and Hashes/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Arrays and Hashes", + "position": 5, + "link": { + "type": "generated-index", + "description": "Learn Arrays and Hashes." + } + } \ No newline at end of file diff --git a/courses/Ruby/beginner-level/Arrays and Hashes/hashes.md b/courses/Ruby/beginner-level/Arrays and Hashes/hashes.md new file mode 100644 index 000000000..902e22f56 --- /dev/null +++ b/courses/Ruby/beginner-level/Arrays and Hashes/hashes.md @@ -0,0 +1,94 @@ +--- +id: lesson-2 +title: "Introduction to Hashes" +sidebar_label: Hashes +sidebar_position: 2 +description: "Introduction to Hashes" +tags: [courses,beginner-level,Ruby,Introduction] +--- + +Hashes are collections of key-value pairs. They are similar to arrays, but the indexing is done via arbitrary keys. + +```ruby +# Creating a hash +person = { name: "Alice", age: 30, city: "New York" } + +# Accessing values +puts person[:name] # Output: Alice + +# Modifying values +person[:age] = 31 +puts person.inspect # Output: {:name=>"Alice", :age=>31, :city=>"New York"} +``` + +#### Hash Methods and Operations +Ruby provides numerous methods to work with hashes. + +```ruby +# Adding key-value pairs +person[:email] = "alice@example.com" +puts person.inspect # Output: {:name=>"Alice", :age=>31, :city=>"New York", :email=>"alice@example.com"} + +# Removing key-value pairs +person.delete(:city) +puts person.inspect # Output: {:name=>"Alice", :age=>31, :email=>"alice@example.com"} + +# Iterating over key-value pairs +person.each do |key, value| + puts "#{key}: #{value}" +end + +# Checking for a key +puts person.key?(:name) # Output: true +puts person.key?(:city) # Output: false +``` + +### Example + +```ruby +# Array example +fruits = ["apple", "banana", "cherry"] +fruits << "date" +fruits.each { |fruit| puts fruit } +# Output: +# apple +# banana +# cherry +# date + +# Hash example +car = { make: "Toyota", model: "Camry", year: 2020 } +car[:color] = "red" +car.each { |key, value| puts "#{key}: #{value}" } +# Output: +# make: Toyota +# model: Camry +# year: 2020 +# color: red +``` + +### Flowchart + +```mermaid +graph TD + A[Start] --> B[Create Array] + B --> C[Add Elements to Array] + C --> D[Access/Modify Array Elements] + D --> E[Iterate Over Array Elements] + E --> F[Create Hash] + F --> G[Add Key-Value Pairs to Hash] + G --> H[Access/Modify Hash Values] + H --> I[Iterate Over Hash Key-Value Pairs] + I --> J[End] +``` + +:::tip +1. **Versatility of Arrays:** + - Ruby arrays can hold objects of any type and provide numerous methods for manipulation, making them very versatile. + +2. **Power of Hashes:** + - Hashes are useful for storing key-value pairs and are highly efficient for lookups, making them ideal for scenarios where association between a key and a value is needed. + +3. **Enumerable Methods:** + - Both arrays and hashes include the Enumerable module, providing powerful methods like `each`, `map`, `select`, and more, allowing for elegant and efficient data manipulation. +::: \ No newline at end of file diff --git a/courses/Ruby/beginner-level/Basic-syntax/Basic-syntax.md b/courses/Ruby/beginner-level/Basic-syntax/Basic-syntax.md new file mode 100644 index 000000000..78879da0d --- /dev/null +++ b/courses/Ruby/beginner-level/Basic-syntax/Basic-syntax.md @@ -0,0 +1,90 @@ +--- +id: lesson-1 +title: "1. Ruby Syntax Basics" +sidebar_label: Ruby Syntax Basics +sidebar_position: 1 +description: "Learn Ruby Syntax Basics" +tags: [courses,beginner-level,Ruby,Introduction] +--- + + +Ruby's syntax is designed to be simple and readable. Here are some fundamental aspects: + +**Comments:** +- Single-line comments start with `#`. +- Multi-line comments are enclosed between `=begin` and `=end`. + +```ruby +# This is a single-line comment + +=begin +This is a +multi-line comment +=end +``` + +**Code Blocks:** +- Code blocks can be enclosed within `do...end` or curly braces `{...}`. + +```ruby +3.times do + puts "Hello!" +end + +3.times { puts "Hello!" } +``` + +**Methods:** +- Methods are defined using the `def` keyword. + +```ruby +def greet(name) + puts "Hello, #{name}!" +end + +greet("Alice") # Outputs: Hello, Alice! +``` + +### 2. Data Types and Variables + +**Common Data Types:** +- **Numbers:** Integer, Float +- **Strings:** Text data +- **Arrays:** Ordered list of elements +- **Hashes:** Key-value pairs +- **Boolean:** `true` or `false` +- **Nil:** Represents "nothing" or "no value" + +```ruby +# Numbers +integer = 42 +float = 3.14 + +# Strings +string = "Hello, World!" + +# Arrays +array = [1, 2, 3, 4, 5] + +# Hashes +hash = { name: "Alice", age: 30 } + +# Boolean +is_ruby_fun = true + +# Nil +nothing = nil +``` + +**Variables:** +- Variables are used to store data and are dynamically typed. + +```ruby +name = "Bob" +age = 25 +is_student = true + +puts name # Outputs: Bob +puts age # Outputs: 25 +puts is_student # Outputs: true +``` diff --git a/courses/Ruby/beginner-level/Basic-syntax/_category_.json b/courses/Ruby/beginner-level/Basic-syntax/_category_.json new file mode 100644 index 000000000..11fb9569f --- /dev/null +++ b/courses/Ruby/beginner-level/Basic-syntax/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Basic Syntax", + "position": 2, + "link": { + "type": "generated-index", + "description": "Learn Basic Syntax of Ruby." + } + } \ No newline at end of file diff --git a/courses/Ruby/beginner-level/Basic-syntax/constants.md b/courses/Ruby/beginner-level/Basic-syntax/constants.md new file mode 100644 index 000000000..811c46bde --- /dev/null +++ b/courses/Ruby/beginner-level/Basic-syntax/constants.md @@ -0,0 +1,77 @@ +--- +id: lesson-2 +title: "Constants and Symbols" +sidebar_label: Constants and Symbols +sidebar_position: 2 +description: "Learn Constants and Symbols in Ruby" +tags: [courses,beginner-level,Ruby,Introduction] +--- + + +**Constants:** +- Constants begin with an uppercase letter and remain unchanged throughout the program. + +```ruby +PI = 3.14159 +MAX_LIMIT = 100 +``` + +**Symbols:** +- Symbols are immutable, reusable constants represented with a colon `:`. + +```ruby +status = :pending +puts status # Outputs: pending +``` + +### Input and Output Operations + +**Output Operations:** +- `puts`: Prints with a newline. +- `print`: Prints without a newline. +- `p`: Prints with `inspect` output (useful for debugging). + +```ruby +puts "Hello, World!" # Outputs: Hello, World! +print "Hello, World!" # Outputs: Hello, World! +p "Hello, World!" # Outputs: "Hello, World!" +``` + +**Input Operations:** +- `gets`: Reads a line from standard input (including the newline character). + +```ruby +puts "Enter your name:" +name = gets.chomp # `chomp` removes the trailing newline character +puts "Hello, #{name}!" +``` + +**Example Program:** + +```ruby +# basic_syntax.rb + +# Declare some variables +name = "Alice" +age = 30 +is_student = false + +# Print a greeting message +puts "Hello, #{name}! You are #{age} years old." + +# Take user input +puts "Enter your favorite number:" +favorite_number = gets.chomp.to_i # Convert input to integer + +# Display user input +puts "Your favorite number is #{favorite_number}." +``` + +**Output:** + +```bash +Hello, Alice! You are 30 years old. +Enter your favorite number: +42 +Your favorite number is 42. +``` \ No newline at end of file diff --git a/courses/Ruby/beginner-level/Control-Strucutre/Loops.md b/courses/Ruby/beginner-level/Control-Strucutre/Loops.md new file mode 100644 index 000000000..347173291 --- /dev/null +++ b/courses/Ruby/beginner-level/Control-Strucutre/Loops.md @@ -0,0 +1,214 @@ +--- +id: lesson-2 +title: "Loops" +sidebar_label: Loops +sidebar_position: 2 +description: "Learn Loops" +tags: [courses,beginner-level,Ruby,Introduction] +--- + + +### Flowchart + +```mermaid +graph TD + J[Loop Start] --> K{Loop Condition} + K -->|true| L[Execute loop block] + L --> J + K -->|false| M[Exit Loop] + M --> E[End] + N[for Loop Start] --> O{Range/Collection} + O --> P[Iterate over elements] + P --> Q[Execute loop block] + Q --> O + O --> R[End] + R --> E[End] +``` + + +**while Loop:** +- Repeats code as long as the condition is true. + +```ruby +i = 1 + +while i <= 5 + puts i + i += 1 +end +``` + +**until Loop:** +- Repeats code as long as the condition is false. + +```ruby +i = 1 + +until i > 5 + puts i + i += 1 +end +``` + +**for Loop:** +- Iterates over a range or collection. + +```ruby +for i in 1..5 + puts i +end +``` + +**each Iterator:** +- Iterates over elements of a collection. + +```ruby +(1..5).each do |i| + puts i +end +``` + +### Iterators and Blocks + +**Block:** +- A block is a chunk of code enclosed in `do...end` or curly braces `{...}` that you can pass to methods. + +```ruby +3.times do + puts "Hello!" +end + +3.times { puts "Hello!" } +``` + +### Break, Next, and Redo Statements + +**break:** +- Exits the loop early. + +```ruby +i = 0 + +while i < 10 + puts i + break if i == 5 + i += 1 +end +``` + +**next:** +- Skips to the next iteration. + +```ruby +for i in 1..10 + next if i % 2 == 0 + puts i +end +``` + +**redo:** +- Repeats the current iteration. + +```ruby +i = 0 + +while i < 10 + puts i + i += 1 + redo if i == 5 +end +``` + +### Example + +```ruby +# control_structures.rb + +# Conditional statements +age = 21 +if age >= 18 + puts "You are an adult." +else + puts "You are a minor." +end + +hungry = true +unless hungry + puts "You are not hungry." +else + puts "You are hungry." +end + +day = "Monday" +case day +when "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" + puts "It's a weekday." +when "Saturday", "Sunday" + puts "It's a weekend." +else + puts "Invalid day." +end + +# Loops +i = 1 +while i <= 3 + puts "While Loop: #{i}" + i += 1 +end + +i = 1 +until i > 3 + puts "Until Loop: #{i}" + i += 1 +end + +for i in 1..3 + puts "For Loop: #{i}" +end + +(1..3).each do |i| + puts "Each Iterator: #{i}" +end + +# Break, next, and redo statements +for i in 1..10 + break if i == 4 + next if i % 2 == 0 + puts "Break/Next: #{i}" +end +``` + +**Output:** + +```bash +You are an adult. +You are hungry. +It's a weekday. +While Loop: 1 +While Loop: 2 +While Loop: 3 +Until Loop: 1 +Until Loop: 2 +Until Loop: 3 +For Loop: 1 +For Loop: 2 +For Loop: 3 +Each Iterator: 1 +Each Iterator: 2 +Each Iterator: 3 +Break/Next: 1 +Break/Next: 3 +``` + +:::tip + +1. **Readable Conditions:** + - Always write conditions that are easy to read and understand. Avoid complex and nested conditions when possible to enhance readability and maintainability. + +2. **Iterators over Loops:** + - Prefer using iterators like `each` over traditional loops (`for`, `while`) as they are more idiomatic and concise in Ruby. + +3. **Early Exit:** + - Use `break`, `next`, and `redo` wisely to control the flow within loops. These can help in managing complex loop conditions and improving readability. +::: + diff --git a/courses/Ruby/beginner-level/Control-Strucutre/_category_.json b/courses/Ruby/beginner-level/Control-Strucutre/_category_.json new file mode 100644 index 000000000..e12afc565 --- /dev/null +++ b/courses/Ruby/beginner-level/Control-Strucutre/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Control Structure", + "position": 3, + "link": { + "type": "generated-index", + "description": "Learn Control Structure in Ruby." + } + } \ No newline at end of file diff --git a/courses/Ruby/beginner-level/Control-Strucutre/statements.md b/courses/Ruby/beginner-level/Control-Strucutre/statements.md new file mode 100644 index 000000000..b5032c9dc --- /dev/null +++ b/courses/Ruby/beginner-level/Control-Strucutre/statements.md @@ -0,0 +1,79 @@ +--- +id: lesson-1 +title: "Conditional Statements" +sidebar_label: Conditional Statements +sidebar_position: 1 +description: "Learn Conditional Statements" +tags: [courses,beginner-level,Ruby,Introduction] +--- + + +#### Flowchart + +```mermaid +graph TD + A[Start] --> B{Condition} + B -->|true| C[if] + C --> D[Execute if block] + D --> E[End] + B -->|false| F[else] + F --> G[Execute else block] + G --> E[End] + B -->|false| H[unless] + H --> I[Execute unless block] + I --> E[End] +``` + +**if Statement:** +- Used to execute code based on a condition. + +```ruby +age = 18 + +if age >= 18 + puts "You are an adult." +else + puts "You are a minor." +end +``` + +**unless Statement:** +- Executes code if the condition is false. + +```ruby +hungry = false + +unless hungry + puts "You are not hungry." +else + puts "You are hungry." +end +``` + +**case-when Statement:** +- Executes code based on multiple conditions. + +```ruby +day = "Saturday" + +case day +when "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" + puts "It's a weekday." +when "Saturday", "Sunday" + puts "It's a weekend." +else + puts "Invalid day." +end +``` + +:::tip + **Readable Switch Statements:** + - Use `case` statements for multiple condition checks instead of multiple `if-elsif-else` blocks to make your code cleaner. + ```ruby + case day + when "Monday" then puts "Start of the week!" + when "Friday" then puts "End of the work week!" + else puts "Midweek" + end + ``` +::: \ No newline at end of file diff --git a/courses/Ruby/beginner-level/Function-and-methods/Category_.json b/courses/Ruby/beginner-level/Function-and-methods/Category_.json new file mode 100644 index 000000000..0277aa64d --- /dev/null +++ b/courses/Ruby/beginner-level/Function-and-methods/Category_.json @@ -0,0 +1,8 @@ +{ + "label": "Functions and Methods", + "position": 4, + "link": { + "type": "generated-index", + "description": "Learn Functions and Methods of Ruby." + } + } \ No newline at end of file diff --git a/courses/Ruby/beginner-level/Function-and-methods/arguments.md b/courses/Ruby/beginner-level/Function-and-methods/arguments.md new file mode 100644 index 000000000..a6eebc761 --- /dev/null +++ b/courses/Ruby/beginner-level/Function-and-methods/arguments.md @@ -0,0 +1,90 @@ +--- +id: lesson-2 +title: "Method Arugument" +sidebar_label: Argument +sidebar_position: 2 +description: "Learn Methods and Arugument" +tags: [courses,beginner-level,Ruby,Introduction] +--- + +Methods can take arguments and return values. By default, the last evaluated expression is returned. + +```ruby +def add(a, b) + return a + b +end + +sum = add(5, 3) +puts sum # Output: 8 +``` + +#### Default and Keyword Arguments +Ruby supports default values for arguments and keyword arguments. + +```ruby +def greet(name="Guest") + puts "Hello, #{name}!" +end + +greet # Output: Hello, Guest! +greet("Alice") # Output: Hello, Alice! + +def order(food:, drink: "water") + puts "Food: #{food}, Drink: #{drink}" +end + +order(food: "Pizza") # Output: Food: Pizza, Drink: water +order(food: "Burger", drink: "Soda") # Output: Food: Burger, Drink: Soda +``` + +#### Yielding to Blocks +Ruby methods can take blocks and yield to them. Blocks are enclosed in `{}` or `do..end`. + +```ruby +def do_something + puts "Before the yield" + yield if block_given? + puts "After the yield" +end + +do_something { puts "Hello from the block!" } +# Output: +# Before the yield +# Hello from the block! +# After the yield +``` + +### Example with Output +Here’s a combined example demonstrating these concepts: + +```ruby +def greet(name="Guest", &block) + message = "Hello, #{name}!" + if block_given? + yield(message) + else + puts message + end +end + +# Calling the method without a block +greet("Alice") +# Output: Hello, Alice! + +# Calling the method with a block +greet("Bob") { |msg| puts msg.upcase } +# Output: HELLO, BOB! +``` + + + +:::tip +1. **Method Flexibility:** + - Methods in Ruby are highly flexible with support for default and keyword arguments, making them powerful and adaptable. + +2. **Blocks and Yielding:** + - Ruby's ability to yield to blocks makes it easy to create methods that can have customized behaviors, enhancing the reusability of code. + +3. **Readable and Concise:** + - Ruby methods promote writing concise and readable code, which is a key principle of Ruby programming, enuring that code is easy to understand and maintain. +::: \ No newline at end of file diff --git a/courses/Ruby/beginner-level/Function-and-methods/define-methods.md b/courses/Ruby/beginner-level/Function-and-methods/define-methods.md new file mode 100644 index 000000000..1d890ca71 --- /dev/null +++ b/courses/Ruby/beginner-level/Function-and-methods/define-methods.md @@ -0,0 +1,33 @@ +--- +id: lesson-1 +title: "Defining and Calling Methods" +sidebar_label: Defining Methods +sidebar_position: 1 +description: "Learn Defining and Calling Methods" +tags: [courses,beginner-level,Ruby,Introduction] +--- + + +In Ruby, methods are defined using the `def` keyword. Here's how to define and call a method: + +```ruby +def greet(name) + puts "Hello, #{name}!" +end + +greet("Alice") # Output: Hello, Alice! +``` + +### Flowchart + +```mermaid +graph TD + A[Start] --> B[Define Method] + B --> C[Method Arguments] + C --> D[Default Arguments] + D --> E[Keyword Arguments] + E --> F[Yielding to Blocks] + F --> G[Call Method without Block] + G --> H[Call Method with Block] + H --> I[End] +``` diff --git a/courses/Ruby/beginner-level/Introduction/_category_.json b/courses/Ruby/beginner-level/Introduction/_category_.json new file mode 100644 index 000000000..fc7739553 --- /dev/null +++ b/courses/Ruby/beginner-level/Introduction/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "What is Ruby & History", + "position": 1, + "link": { + "type": "generated-index", + "description": "Learn Ruby & History." + } + } \ No newline at end of file diff --git a/courses/Ruby/beginner-level/Introduction/setup.md b/courses/Ruby/beginner-level/Introduction/setup.md new file mode 100644 index 000000000..47af622da --- /dev/null +++ b/courses/Ruby/beginner-level/Introduction/setup.md @@ -0,0 +1,58 @@ +--- +id: lesson-2 +title: "Setting Up the Development Environment" +sidebar_label: Setting Up +sidebar_position: 2 +description: "Learn Setting Up the Development Environment" +tags: [courses,beginner-level,Ruby,Introduction] +--- + + +**Step 1: Install Ruby** + +To install Ruby, you can use a version manager like RVM (Ruby Version Manager) or rbenv. Here we'll use RVM. + +**Install RVM:** + +```bash +\curl -sSL https://get.rvm.io | bash -s stable +``` + +**Install Ruby:** + +```bash +rvm install ruby +rvm use ruby --default +``` + +**Step 2: Verify Installation** + +```bash +ruby -v +# This should output the Ruby version, e.g., ruby 3.1.2 +``` + +### Writing and Running Your First Ruby Program + +**Step 1: Write the Program** + +Create a file named `hello_world.rb` and open it in your favorite text editor. Add the following code: + +```ruby +# hello_world.rb +puts 'Hello, World!' +``` + +**Step 2: Run the Program** + +Open your terminal and navigate to the directory where `hello_world.rb` is located. Run the program using the following command: + +```bash +ruby hello_world.rb +``` + +**Output:** + ```bash + Hello, World! + ``` + \ No newline at end of file diff --git a/courses/Ruby/beginner-level/Introduction/what-is-ruby.md b/courses/Ruby/beginner-level/Introduction/what-is-ruby.md new file mode 100644 index 000000000..bb3782be6 --- /dev/null +++ b/courses/Ruby/beginner-level/Introduction/what-is-ruby.md @@ -0,0 +1,24 @@ +--- +id: lesson-1 +title: "What is Ruby?" +sidebar_label: Introduction & History +sidebar_position: 1 +description: "Learn Introduction to Ruby & History" +tags: [courses,beginner-level,Ruby,Introduction] +--- + + +**Ruby** is a dynamic, open-source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write. Ruby is widely known for its use in web development, particularly with the Ruby on Rails framework. + +:::note +**Features:** +- **Object-Oriented:** Everything in Ruby is an object, including primitive data types. +- **Dynamic Typing:** Types are determined at runtime. +- **Garbage Collection:** Automatic memory management. +- **Flexibility:** Ruby allows for modification of its parts, making it highly customizable. +- **Community and Libraries:** A strong community and a wealth of libraries (gems) available for various tasks. +::: + +### History and Evolution of Ruby + +**Ruby** was created by Yukihiro "Matz" Matsumoto in the mid-1990s. The first public release was in 1995. Ruby was designed to be more powerful than Perl and more object-oriented than Python. Over the years, Ruby has grown in popularity, especially with the advent of the Ruby on Rails framework in 2004, which greatly boosted its adoption for web development. diff --git a/courses/Ruby/beginner-level/Strings/_category_.json b/courses/Ruby/beginner-level/Strings/_category_.json new file mode 100644 index 000000000..454a63f74 --- /dev/null +++ b/courses/Ruby/beginner-level/Strings/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Strings", + "position": 4, + "link": { + "type": "generated-index", + "description": "Learn Strings Concepts in Ruby." + } + } \ No newline at end of file diff --git a/courses/Ruby/beginner-level/Strings/concepts.md b/courses/Ruby/beginner-level/Strings/concepts.md new file mode 100644 index 000000000..c98946a56 --- /dev/null +++ b/courses/Ruby/beginner-level/Strings/concepts.md @@ -0,0 +1,133 @@ +--- +id: lesson-1 +title: "String Creation and Manipulation" +sidebar_label: String Concept +sidebar_position: 1 +description: "Learn String Concepts" +tags: [courses,beginner-level,Ruby,Introduction] +--- + +Strings in Ruby can be created using single quotes, double quotes, or the `String` class. + +```ruby +# Creating strings +single_quote_string = 'Hello, world!' +double_quote_string = "Hello, world!" +string_class_string = String.new("Hello, world!") + +# Accessing characters +puts single_quote_string[0] # Output: H + +# Modifying strings +single_quote_string[0] = 'J' +puts single_quote_string # Output: Jello, world! +``` + +#### String Interpolation and Concatenation +String interpolation allows embedding expressions inside string literals. Concatenation joins strings together. + +```ruby +name = "Alice" +greeting = "Hello, #{name}!" +puts greeting # Output: Hello, Alice! + +# Concatenation +full_greeting = "Hello, " + name + "!" +puts full_greeting # Output: Hello, Alice! + +# Using the shovel operator (<<) +greeting << " How are you?" +puts greeting # Output: Hello, Alice! How are you? +``` + +#### String Methods +Ruby provides many methods for string manipulation. + +```ruby +# Length +puts greeting.length # Output: 20 + +# Split +words = greeting.split(" ") +puts words.inspect # Output: ["Hello,", "Alice!", "How", "are", "you?"] + +# Replace (gsub) +new_greeting = greeting.gsub("Alice", "Bob") +puts new_greeting # Output: Hello, Bob! How are you? + +# Upcase and Downcase +puts greeting.upcase # Output: HELLO, ALICE! HOW ARE YOU? +puts greeting.downcase # Output: hello, alice! how are you? +``` + +#### Regular Expressions +Regular expressions are used for pattern matching and text manipulation. + +```ruby +text = "The price is $100." +# Check for pattern +puts text =~ /\$[0-9]+/ # Output: 13 + +# Extracting the pattern +price = text[/\$[0-9]+/] +puts price # Output: $100 + +# Replacing text using regex +new_text = text.gsub(/\$[0-9]+/, "$200") +puts new_text # Output: The price is $200. +``` + +### Example with Output +Here's an example demonstrating the concepts: + +```ruby +name = "Alice" +greeting = "Hello, #{name}!" +full_greeting = greeting + " How are you today?" +puts full_greeting + +# String methods +puts "Length: #{full_greeting.length}" +puts "Words: #{full_greeting.split(" ").inspect}" +puts "Uppercase: #{full_greeting.upcase}" + +# Regular expressions +if full_greeting =~ /Alice/ + puts "The string contains 'Alice'." +else + puts "The string does not contain 'Alice'." +end + +``` +## Output: +```bash + Hello, Alice! How are you today? + Length: 27 + Words: ["Hello", "Alice!", "How", "are", "you", "today?"] + Uppercase: HELLO, ALICE! HOW ARE YOU TODAY? + The string contains 'Alice'. +``` +:::important +1. **String Interpolation**: Allows embedding variables and expressions within strings using `#{}`. +2. **String Methods**: Ruby provides extensive methods like `length`, `split`, `gsub`, etc., for effective string manipulation. +3. **Regular Expressions**: Powerful for pattern matching and text processing, enabling sophisticated string operations. +::: + +### Flowchart + +```mermaid +graph TD + A[Start] --> B[Create Strings] + B --> C[Concatenate Strings] + C --> D[Interpolate Strings] + D --> E[Use String Methods] + E --> F[Apply Regular Expressions] + F --> G[End] +``` + + +:::tip +- Use single quotes for strings that don't need interpolation or special character processing for slight performance benefits. +- Familiarize yourself with Ruby's extensive string methods to handle common tasks efficiently. +- Regular expressions are a powerful tool but can be complex; practice to understand their syntax and capabilities. +::: \ No newline at end of file diff --git a/courses/Ruby/beginner-level/_category_.json b/courses/Ruby/beginner-level/_category_.json new file mode 100644 index 000000000..f94868d42 --- /dev/null +++ b/courses/Ruby/beginner-level/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Beginner Level", + "position": 2, + "link": { + "type": "generated-index", + "description": "Learn Beginner Concepts of Ruby." + } + } \ No newline at end of file diff --git a/courses/Ruby/intermediate-level/Enumerables-and-Iteration/_category_.json b/courses/Ruby/intermediate-level/Enumerables-and-Iteration/_category_.json new file mode 100644 index 000000000..e4ea4f25f --- /dev/null +++ b/courses/Ruby/intermediate-level/Enumerables-and-Iteration/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Enumerables and Iterators", + "position": 2, + "link": { + "type": "generated-index", + "description": "Learn Enumerables and Iterators." + } + } \ No newline at end of file diff --git a/courses/Ruby/intermediate-level/Enumerables-and-Iteration/custom-iterations.md b/courses/Ruby/intermediate-level/Enumerables-and-Iteration/custom-iterations.md new file mode 100644 index 000000000..9773a1b12 --- /dev/null +++ b/courses/Ruby/intermediate-level/Enumerables-and-Iteration/custom-iterations.md @@ -0,0 +1,59 @@ +--- +id: lesson-2 +title: "Custom Iterators with Enumerator" +sidebar_label: Custom Iterators with Enumerator +sidebar_position: 2 +description: "Learn Custom Iterators with Enumerator" +tags: [courses,intermediate-level,Ruby,Introduction] +--- + + +You can create custom iterators using the `Enumerator` class. + +```ruby +enum = Enumerator.new do |yielder| + (1..5).each { |i| yielder << i } +end + +enum.each { |item| puts item } +``` + +**Output:** + +```bash +1 +2 +3 +4 +5 +``` + +#### Lazy Enumerables + +Lazy enumerables are useful for working with large data sets as they allow processing data on-demand. + +```ruby +lazy_numbers = (1..Float::INFINITY).lazy.select { |n| n.even? }.take(5) +lazy_numbers.each { |n| puts n } +``` + +**Output:** + +```bash +2 +4 +6 +8 +10 +``` +:::tip + +1. **Leverage Built-in Methods**: + - Ruby’s `Enumerable` module provides a rich set of methods like `map`, `select`, `reduce`, and `reject` that can simplify many common operations on collections. Always consider using these built-in methods for concise and readable code. + +2. **Custom Iterators**: + - When implementing custom iterators, ensure you define the `each` method properly to yield each element to the block. This allows your class to work seamlessly with enumerable methods and provides greater flexibility for custom data structures. + +3. **Use Lazy Enumerables for Large Data**: + - When working with potentially large data sets or expensive operations, use lazy enumerables to defer computation and process items on-demand. This can significantly improve performance and reduce memory usage by avoiding the creation of intermediate collections. +::: \ No newline at end of file diff --git a/courses/Ruby/intermediate-level/Enumerables-and-Iteration/working-with-Enumerables.md b/courses/Ruby/intermediate-level/Enumerables-and-Iteration/working-with-Enumerables.md new file mode 100644 index 000000000..77bfce0c9 --- /dev/null +++ b/courses/Ruby/intermediate-level/Enumerables-and-Iteration/working-with-Enumerables.md @@ -0,0 +1,84 @@ +--- +id: lesson-1 +title: "Enumerables and Iterators in Rubyr" +sidebar_label: Enumerables +sidebar_position: 1 +description: "Learn Enumerables and Iterators in Ruby" +tags: [courses,intermediate-level,Ruby,Introduction] +--- + + +Ruby provides robust support for working with collections through the `Enumerable` module. Here’s how you can utilize various enumerable methods and custom iterators. + +#### Working with Enumerables + +A class needs to include the `Enumerable` module and implement the `each` method to use enumerable methods. + +```ruby +class CustomCollection + include Enumerable + + def initialize(items) + @items = items + end + + def each(&block) + @items.each(&block) + end +end + +collection = CustomCollection.new([1, 2, 3, 4, 5]) +collection.each { |item| puts item } +``` + +**Output:** + +```bash +1 +2 +3 +4 +5 +``` + +#### Common Enumerable Methods + +- **`map`**: Transforms elements based on the given block. + +```ruby +numbers = [1, 2, 3, 4, 5] +squared_numbers = numbers.map { |n| n ** 2 } +puts squared_numbers.inspect +``` + +**Output:** + +```bash +[1, 4, 9, 16, 25] +``` + +- **`select`**: Filters elements based on the given block. + +```ruby +even_numbers = numbers.select { |n| n.even? } +puts even_numbers.inspect +``` + +**Output:** + +```bash +[2, 4] +``` + +- **`reduce`**: Reduces elements to a single value based on the given block. + +```ruby +sum = numbers.reduce(0) { |acc, n| acc + n } +puts sum +``` + +**Output:** + +```bash +15 +``` diff --git a/courses/Ruby/intermediate-level/Gems-and-builder/_category_.json b/courses/Ruby/intermediate-level/Gems-and-builder/_category_.json new file mode 100644 index 000000000..20368ccb7 --- /dev/null +++ b/courses/Ruby/intermediate-level/Gems-and-builder/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Gems and Bundler", + "position": 4, + "link": { + "type": "generated-index", + "description": "Learn Gems and Bundler." + } + } \ No newline at end of file diff --git a/courses/Ruby/intermediate-level/Gems-and-builder/intro.md b/courses/Ruby/intermediate-level/Gems-and-builder/intro.md new file mode 100644 index 000000000..b9987d710 --- /dev/null +++ b/courses/Ruby/intermediate-level/Gems-and-builder/intro.md @@ -0,0 +1,49 @@ +--- +id: lesson-1 +title: "Gems and Bundler in Ruby" +sidebar_label: Intro & Uses +sidebar_position: 1 +description: "Gems and Bundler in Ruby" +tags: [courses,intermediate-level,Ruby,Introduction] +--- + + +**RubyGems** is a package manager for Ruby, allowing you to manage libraries (gems) and their dependencies. **Bundler** is a tool that helps manage gem dependencies for your Ruby projects. + +#### **1. Introduction to RubyGems** + +- **What is RubyGems?** + - RubyGems is the standard way to distribute and manage Ruby libraries. Each library is packaged into a gem, which is a compressed file containing Ruby code, metadata, and a gemspec file. + +:::note +- **Common Commands**: + - **`gem install `**: Install a gem. + - **`gem list`**: List installed gems. + - **`gem update`**: Update installed gems. + - **`gem uninstall `**: Uninstall a gem. +::: + +#### **2. Installing and Using Gems** + +- **Installation**: + - To install a gem, use the `gem install` command followed by the gem name. + + **Example**: + ```bash + gem install nokogiri + ``` + +- **Using Gems in Your Code**: + - To use a gem in your Ruby code, require it at the beginning of your script. + + **Example**: + ```ruby + require 'nokogiri' + + doc = Nokogiri::HTML("Hello World") + puts doc.at('body').text + ``` + **Output**: + ```bash + Hello World + ``` \ No newline at end of file diff --git a/courses/Ruby/intermediate-level/Gems-and-builder/publishing.md b/courses/Ruby/intermediate-level/Gems-and-builder/publishing.md new file mode 100644 index 000000000..20919b4be --- /dev/null +++ b/courses/Ruby/intermediate-level/Gems-and-builder/publishing.md @@ -0,0 +1,92 @@ +--- +id: lesson-2 +title: "Creating and Publishing Your Own Gem" +sidebar_label: Publish Gem +sidebar_position: 2 +description: "Creating and Publishing Your Own Gem" +tags: [courses,intermediate-level,Ruby,Introduction] +--- + + +- **Creating a Gem**: + 1. **Setup**: Install Bundler and create a new gem skeleton. + ```bash + gem install bundler + bundler gem my_gem + ``` + 2. **Edit the Gem Specification**: Modify the `.gemspec` file with your gem’s details. + 3. **Add Code**: Place your Ruby code in the `lib/` directory. + 4. **Build the Gem**: + ```bash + gem build my_gem.gemspec + ``` + 5. **Install Locally** (optional): + ```bash + gem install ./my_gem-0.1.0.gem + ``` + +- **Publishing Your Gem**: + - **Sign Up**: Create an account on [RubyGems.org](https://rubygems.org). + - **Push Your Gem**: + ```bash + gem push my_gem-0.1.0.gem + ``` + +#### **Managing Dependencies with Bundler** + +- **What is Bundler?** + - Bundler manages gem dependencies for Ruby projects, ensuring that the exact versions of gems required are installed. + +- **Setting Up Bundler**: + 1. **Create a `Gemfile`**: List your gem dependencies. + ```ruby + source 'https://rubygems.org' + gem 'nokogiri' + gem 'rails', '~> 6.1.0' + ``` + 2. **Install Gems**: + ```bash + bundle install + ``` + +:::tip + +1. **Use `bundle exec`**: + - Always use `bundle exec` to run commands that depend on your project’s gems to ensure you're using the correct gem versions. + +2. **Keep Your Gems Up-to-Date**: + - Regularly update your gems and test your application to ensure compatibility with newer versions. + +3. **Be Careful with Version Constraints**: + - Use version constraints in your `Gemfile` to avoid unexpected behavior from gem updates. For example, `gem 'rails', '~> 6.1.0'` ensures that only patch-level updates are allowed. +::: + +- **Using Bundler**: + - **Check Dependencies**: + ```bash + bundle show + ``` + - **Update Gems**: + ```bash + bundle update + ``` + +- **Running Commands**: + - **Run a Ruby script with Bundler**: + ```bash + bundle exec ruby my_script.rb + ``` + + + +:::important + +1. **Gem Dependencies**: + - Clearly define your gem dependencies in the `Gemfile` to maintain consistency across different environments. + +2. **Gem Security**: + - Regularly audit your gem dependencies for vulnerabilities using tools like [bundler-audit](https://github.com/rubysec/bundler-audit). + +3. **Gem Documentation**: + - Ensure your gem includes adequate documentation and usage instructions to help others understand how to use it effectively. +::: \ No newline at end of file diff --git a/courses/Ruby/intermediate-level/OOPS/_category_.json b/courses/Ruby/intermediate-level/OOPS/_category_.json new file mode 100644 index 000000000..6dcce7957 --- /dev/null +++ b/courses/Ruby/intermediate-level/OOPS/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Advanced OOPS Concept", + "position": 1, + "link": { + "type": "generated-index", + "description": "Learn Advanced OOPS Concept." + } + } \ No newline at end of file diff --git a/courses/Ruby/intermediate-level/OOPS/concepts.md b/courses/Ruby/intermediate-level/OOPS/concepts.md new file mode 100644 index 000000000..871545c7f --- /dev/null +++ b/courses/Ruby/intermediate-level/OOPS/concepts.md @@ -0,0 +1,231 @@ +--- +id: lesson-1 +title: "Advanced Object-Oriented Programming (OOP) in Ruby" +sidebar_label: OOPS Overall View +sidebar_position: 1 +description: "Learn Advanced Object-Oriented Programming (OOP) in Ruby" +tags: [courses,intermediate-level,Ruby,Introduction] +--- + +#### Introduction to OOP Concepts +Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to structure code. Ruby, being an object-oriented language, makes heavy use of these concepts. + +:::note +- **Classes and Objects**: Classes are blueprints for objects. Objects are instances of classes. +- **Instance Variables and Methods**: Instance variables are variables that belong to an instance of a class. Instance methods are functions defined in a class that operate on instance variables. +- **Class Variables and Methods**: Class variables are variables that belong to the class itself. Class methods are functions defined on the class, not instances. +::: + +#### Classes and Objects + +```ruby +class Person + # Class variable + @@population = 0 + + # Constructor + def initialize(name, age) + @name = name # Instance variable + @age = age # Instance variable + @@population += 1 + end + + # Instance method + def introduce + "Hello, my name is #{@name} and I am #{@age} years old." + end + + # Class method + def self.population + @@population + end +end + +# Creating objects +alice = Person.new("Alice", 30) +bob = Person.new("Bob", 25) + +puts alice.introduce # Output: Hello, my name is Alice and I am 30 years old. +puts bob.introduce # Output: Hello, my name is Bob and I am 25 years old. +puts Person.population # Output: 2 +``` + +#### Inheritance +Inheritance allows a class to inherit features from another class. + +```ruby +class Animal + def speak + "Some sound" + end +end + +class Dog < Animal + def speak + "Woof!" + end +end + +dog = Dog.new +puts dog.speak # Output: Woof! +``` + +#### Method Overriding and `super` +Method overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass. + +```ruby +class Animal + def speak + "Some sound" + end +end + +class Cat < Animal + def speak + super + " Meow!" # Calling the superclass method + end +end + +cat = Cat.new +puts cat.speak # Output: Some sound Meow! +``` + +#### Polymorphism +Polymorphism allows methods to behave differently based on the object calling them. + +```ruby +class Animal + def speak + "Some sound" + end +end + +class Dog < Animal + def speak + "Woof!" + end +end + +class Cat < Animal + def speak + "Meow!" + end +end + +animals = [Dog.new, Cat.new, Animal.new] +animals.each { |animal| puts animal.speak } +# Output: +# Woof! +# Meow! +# Some sound +``` + +#### Encapsulation and Access Control +Encapsulation restricts direct access to some of an object's components, which is a means of preventing unintended interference and misuse. + +```ruby +class Person + def initialize(name, age) + @name = name + @age = age + end + + # Getter method + def name + @name + end + + # Setter method + def name=(new_name) + @name = new_name + end + + # Private method + private + def age + @age + end +end + +person = Person.new("Alice", 30) +puts person.name # Output: Alice +person.name = "Bob" +puts person.name # Output: Bob +# puts person.age # This will raise an error: private method `age' called +``` + +### Example with Output +Here's a full example demonstrating the concepts: + +```ruby +class Vehicle + @@count = 0 + + def initialize(make, model) + @make = make + @model = model + @@count += 1 + end + + def description + "This is a #{@make} #{@model}." + end + + def self.count + @@count + end +end + +class Car < Vehicle + def description + super + " It's a car." + end +end + +class Motorcycle < Vehicle + def description + super + " It's a motorcycle." + end +end + +car = Car.new("Toyota", "Camry") +motorcycle = Motorcycle.new("Harley-Davidson", "Iron 883") + +puts car.description # Output: This is a Toyota Camry. It's a car. +puts motorcycle.description # Output: This is a Harley-Davidson Iron 883. It's a motorcycle. +puts Vehicle.count # Output: 2 +``` + +:::important +1. **Encapsulation**: Restricts access to certain parts of an object to prevent unintended interference. +2. **Inheritance**: Allows a class to inherit attributes and methods from another class, promoting code reuse. +3. **Polymorphism**: Enables a single method to operate differently based on the calling object, enhancing flexibility. +::: + +### Flowchart + +```mermaid +graph TD + A[Class: Vehicle] + B[Class: Car] + C[Class: Motorcycle] + D[Instance: car] + E[Instance: motorcycle] + F[Class: Animal] + G[Class: Dog] + H[Class: Cat] + + A -->|inherits| B + A -->|inherits| C + B -->|creates| D + C -->|creates| E + F -->|inherits| G + F -->|inherits| H +``` + + +:::tip +- Use `super` to call methods from the superclass when overriding. +- Encapsulate sensitive data by using private or protected access controls. +- Leverage polymorphism to write more generic and reusable code. +::: \ No newline at end of file diff --git a/courses/Ruby/intermediate-level/_category_.json b/courses/Ruby/intermediate-level/_category_.json new file mode 100644 index 000000000..9171f2c2b --- /dev/null +++ b/courses/Ruby/intermediate-level/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Intermediate Level", + "position": 3, + "link": { + "type": "generated-index", + "description": "Learn Ruby Concept." + } + } \ No newline at end of file diff --git a/courses/Ruby/intermediate-level/metaprogramming/Dynamic-method.md b/courses/Ruby/intermediate-level/metaprogramming/Dynamic-method.md new file mode 100644 index 000000000..df673a5b4 --- /dev/null +++ b/courses/Ruby/intermediate-level/metaprogramming/Dynamic-method.md @@ -0,0 +1,68 @@ +--- +id: lesson-2 +title: "Methods Dynamically" +sidebar_label: Dynamic Method +sidebar_position: 2 +description: "Learn Methods Dynamically in Ruby" +tags: [courses,intermediate-level,Ruby,Introduction] +--- + + +#### **3. Defining Methods Dynamically** +- You can define methods dynamically using `define_method`. This is useful for creating methods based on runtime conditions or data. + + **Example**: + ```ruby + class DynamicClass + define_method(:dynamic_method) do |arg| + "Dynamic method called with #{arg}" + end + end + + obj = DynamicClass.new + puts obj.dynamic_method("example") + ``` + **Output**: + ```bash + Dynamic method called with example + ``` + +#### **4. Understanding Hooks** +- Hooks are special methods that are triggered by specific events, such as including or inheriting modules. + + **Example**: + ```ruby + module HookExample + def self.included(base) + puts "#{base} included HookExample" + end + + def self.extended(base) + puts "#{base} extended HookExample" + end + end + + class TestClass + include HookExample + end + + class AnotherClass + extend HookExample + end + ``` + **Output**: + ```bash + TestClass included HookExample + AnotherClass extended HookExample + ``` + +:::tip +1. **Use Metaprogramming Sparingly**: + - Metaprogramming can lead to code that’s hard to understand and maintain. Apply it only when it simplifies or adds significant value to your code. + +2. **Document Metaprogramming Code**: + - Clearly document why and how metaprogramming techniques are used. This will help others (and yourself) understand the purpose and mechanics of your code. + +3. **Handle Errors Gracefully**: + - When using methods like `method_missing`, ensure you handle unexpected method calls or arguments gracefully to prevent runtime errors. +::: \ No newline at end of file diff --git a/courses/Ruby/intermediate-level/metaprogramming/_category_.json b/courses/Ruby/intermediate-level/metaprogramming/_category_.json new file mode 100644 index 000000000..be06b554f --- /dev/null +++ b/courses/Ruby/intermediate-level/metaprogramming/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Metaprogramming", + "position": 3, + "link": { + "type": "generated-index", + "description": "Learn Metaprogramming." + } + } \ No newline at end of file diff --git a/courses/Ruby/intermediate-level/metaprogramming/intro.md b/courses/Ruby/intermediate-level/metaprogramming/intro.md new file mode 100644 index 000000000..0febfc6e0 --- /dev/null +++ b/courses/Ruby/intermediate-level/metaprogramming/intro.md @@ -0,0 +1,54 @@ +--- +id: lesson-1 +title: "Metaprogramming" +sidebar_label: Introduction +sidebar_position: 1 +description: "Learn Metaprogramming in Ruby" +tags: [courses,intermediate-level,Ruby,Introduction] +--- + + +Metaprogramming allows Ruby developers to write code that can modify or create methods dynamically. Here’s an overview of key concepts and practical examples. + +#### **1. Introduction to Metaprogramming** +Metaprogramming involves writing code that can alter itself or other code at runtime. Ruby's dynamic nature makes it particularly suited for metaprogramming. + +#### **2. Using `send` and `method_missing`** + +- **`send` Method**: + - `send` is used to call a method by its name, which can be a symbol or string. It can also bypass private and protected method access controls. + + **Example**: + ```ruby + class Example + def greet(name) + "Hello, #{name}!" + end + end + + example = Example.new + puts example.send(:greet, "Alice") + ``` + **Output**: + ```bash + Hello, Alice! + ``` + +- **`method_missing` Method**: + - `method_missing` is invoked when a method that doesn’t exist is called. This method can be overridden to handle undefined method calls dynamically. + + **Example**: + ```ruby + class DynamicMethods + def method_missing(name, *args) + "You called #{name} with #{args.inspect}" + end + end + + obj = DynamicMethods.new + puts obj.unknown_method("test") + ``` + **Output**: + ```bash + You called unknown_method with ["test"] + ``` diff --git a/courses/Ruby/intermediate-level/working-with-API/JSON-and-XML.md b/courses/Ruby/intermediate-level/working-with-API/JSON-and-XML.md new file mode 100644 index 000000000..ec797e79b --- /dev/null +++ b/courses/Ruby/intermediate-level/working-with-API/JSON-and-XML.md @@ -0,0 +1,100 @@ +--- +id: lesson-2 +title: "Parsing JSON and XML" +sidebar_label: JSON and XML +sidebar_position: 2 +description: "Learn JSON and XML" +tags: [courses,intermediate-level,Ruby,Introduction] +--- + + +**Parsing JSON**: +- JSON is a common format for API responses. Ruby provides a built-in `JSON` library for parsing. + + **Example**: + ```ruby + require 'json' + + json_string = '{"name": "John", "age": 30}' + parsed_data = JSON.parse(json_string) + + puts parsed_data['name'] # Output: John + ``` + +**Parsing XML**: +- XML parsing can be done using libraries like `Nokogiri`. + + **Example**: + ```ruby + require 'nokogiri' + + xml_string = 'John30' + doc = Nokogiri::XML(xml_string) + + puts doc.at_xpath('//name').text # Output: John + ``` + +#### **Creating a Simple REST API** + +- A simple REST API can be created using the `sinatra` gem. + + **Example**: + ```ruby + require 'sinatra' + require 'json' + + get '/api/hello' do + content_type :json + { message: 'Hello, world!' }.to_json + end + + # To run: `ruby app.rb` + ``` + + **Test with `curl`**: + ```bash + curl http://localhost:4567/api/hello + ``` + + **Output**: + ```bash + {"message":"Hello, world!"} + ``` + +#### **Consuming Third-Party APIs** + +- Use HTTP clients like `Net::HTTP` or `HTTParty` to interact with third-party APIs. + + **Example with `HTTParty`**: + ```ruby + require 'httparty' + + response = HTTParty.get('https://api.github.com/users/octocat') + user = response.parsed_response + + puts "User: #{user['login']}" + puts "Bio: #{user['bio']}" + ``` + + **Output**: + ```bash + User: octocat + Bio: A mysterious octocat + ``` + +:::tip +1. **Check API Documentation**: + - Always refer to the API documentation for details on endpoints, parameters, and response formats. + +2. **Authentication**: + - Many APIs require authentication (e.g., API keys, OAuth). Ensure you include necessary credentials in your requests. + +3. **Data Parsing**: + - Be prepared to handle and parse different data formats (JSON, XML) based on the API's response. + +4. **Handle Errors Gracefully**: + - Implement error handling to manage issues such as network errors or invalid responses. + +5. **Respect Rate Limits**: + - Be aware of rate limits set by the API provider to avoid being blocked. +::: \ No newline at end of file diff --git a/courses/Ruby/intermediate-level/working-with-API/_category_.json b/courses/Ruby/intermediate-level/working-with-API/_category_.json new file mode 100644 index 000000000..52fdca119 --- /dev/null +++ b/courses/Ruby/intermediate-level/working-with-API/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Working With APIs", + "position": 5, + "link": { + "type": "generated-index", + "description": "Learn APIs Handling in Ruby." + } + } \ No newline at end of file diff --git a/courses/Ruby/intermediate-level/working-with-API/http.md b/courses/Ruby/intermediate-level/working-with-API/http.md new file mode 100644 index 000000000..6e47c73f9 --- /dev/null +++ b/courses/Ruby/intermediate-level/working-with-API/http.md @@ -0,0 +1,60 @@ +--- +id: lesson-1 +title: "Working with APIs in Ruby" +sidebar_label: Dynamic Method +sidebar_position: 1 +description: "Learn Handling APIs in Ruby" +tags: [courses,intermediate-level,Ruby,Introduction] +--- + +APIs (Application Programming Interfaces) allow different software applications to communicate with each other. Ruby provides several libraries for making HTTP requests and handling API responses. + +#### **1. Making HTTP Requests** + +**Using `Net::HTTP`**: +- `Net::HTTP` is Ruby's standard library for making HTTP requests. + + **Example**: + ```ruby + require 'net/http' + require 'json' + + url = URI.parse('https://jsonplaceholder.typicode.com/posts/1') + response = Net::HTTP.get_response(url) + data = JSON.parse(response.body) + + puts data + ``` + + **Output**: + ```bash + { + "userId": 1, + "id": 1, + "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", + "body": "quia et suscipit\nsuscipit...nesciunt" + } + ``` + +**Using `HTTParty`**: +- `HTTParty` is a gem that simplifies making HTTP requests. + + **Example**: + ```ruby + require 'httparty' + + response = HTTParty.get('https://jsonplaceholder.typicode.com/posts/1') + data = response.parsed_response + + puts data + ``` + + **Output**: + ```bash + { + "userId": 1, + "id": 1, + "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", + "body": "quia et suscipit\nsuscipit...nesciunt" + } + ``` \ No newline at end of file