# KODACAMP 1st week # Day 1 On macOS, Ruby is pre-installed as part of the operating system. Apple includes Ruby in macOS to provide users with a programming language and development environment out-of-the-box. ### Printing `puts` is primarily used to display output on a new line. It automatically adds a newline character (\n) at the end of the output ```ruby= puts "Hello" puts "World" ``` The print method, as the name suggests, prints the output without adding a newline character. It keeps the output on the same line ```ruby= print "Hello /n" print "World" print "Hello" print "World" ``` ```ruby= p "Hello" p "World" ``` ### Variables #### Variable Naming * Variable names in Ruby are case-sensitive and must start with a lowercase letter or an underscore (_). * They can contain alphanumeric characters and underscores, but they cannot start with a number. * It is recommended to use descriptive names that convey the purpose of the variable. ```ruby= name = 'bernard' student_id = 9 student_address = 'Makati City' ``` #### Variable Assignment Variables are assigned values using the assignment operator (=). The value on the right side of the operator is assigned to the variable on the left side. ```ruby= name = "John" age = 30 puts "My name is #{name}" puts "I am #{age} years old" student_name = name student_age = age puts "My name is #{student_name}" puts "I am #{student_age} years old" ``` #### interpolation and concatenation String interpolation is often favored for its conciseness, especially when multiple variables are involved, leading to cleaner and more readable code. It also simplifies the process of mixing different data types, like strings and numbers, without requiring explicit conversions. For example, unlike the + operator, which causes an error when combining a string and a number, string interpolation handles this effortlessly. ```ruby puts "I am the number " + 3 # returns error ``` ```ruby puts "I am the number #{3}" ``` # Day 2 **Introduction to Arrays:** Start by explaining what an array is in the context of programming. An array is an ordered collection of elements, where each element is identified by an index (a numerical position). In Ruby, arrays can contain any combination of data types, including numbers, strings, other arrays, or objects. **Creating Arrays:** Show how to create arrays in Ruby using square brackets [] or the Array.new constructor: ```ruby= my_array = [1, 2, 3, 4, 5] empty_array = [] ``` **Accessing Elements:** Explain how to access elements in an array using their indices, which start at 0: ```ruby= my_array[0] # Access the first element (1) my_array[2] # Access the third element (3) ``` **Modifying Arrays:** Teach how to add elements to an array, remove elements, and modify existing elements: **Adding elements:** ```ruby= my_array << 6 # Appends 6 to the end my_array.push(7) # Also appends 7 to the end ``` **Removing elements:** ```ruby= my_array.pop # Removes and returns the last element my_array.delete_at(2) # Removes the element at index 2 ``` **Modifying elements:** ```ruby= my_array[1] = 10 # Changes the second element to 10 ``` **Array Methods:** Introduce common array methods such as length, empty?, include?, and each: ```ruby= my_array.length # Get the number of elements in the array my_array.empty? # Check if the array is empty my_array.include?(3) # Check if 3 is in the array my_array.each { |element| puts element } # Iterate over each element ``` **Iterating Over Arrays:** Teach how to use loops (e.g., each) to iterate through an array and perform operations on its elements. **Array Slicing:** Explain how to extract a portion of an array using slicing: ```ruby= my_array[1..3] # Returns a new array containing elements at indices 1, 2, and 3 ``` **Common Array Operations:** Discuss common operations like sorting, reversing, and joining arrays: ```ruby= my_array.sort # Sorts the elements in ascending order my_array.reverse # Reverses the order of elements my_array.join(", ") # Joins elements into a string with a separator ``` **Multidimensional Arrays:** Mention that arrays can also be used to create multidimensional arrays ```ruby= matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] ``` **1. What is a Hash?** Start by explaining that a hash (also known as a dictionary or associative array in other programming languages) is a data structure in Ruby that stores data in key-value pairs. Emphasize that unlike arrays, which use numeric indices, hashes use keys to access their values. Keys can be of any data type, often symbols or strings. Mention that hashes are useful for associating information and for fast data retrieval based on keys. **2. Creating Hashes** Show how to create a hash using curly braces {} and the => (hash rocket) syntax: ```ruby= my_hash = { "name" => "John", "age" => 30, "city" => "New York" } my_hash = { name: "John", age: 30, city: "New York" } my_hash = { :name => "John", :age => 30, :city => "New York" } ``` **3. Accessing Values** Explain how to access values in a hash using their keys: ```ruby= my_hash["name"] # Access value associated with the key "name" my_hash[:name] # Access value using a symbol key ``` **4. Modifying Hashes** Teach how to add, update, and delete key-value pairs in a hash: ```ruby my_hash["job"] = "Engineer" # Adding a new pair my_hash[:age] = 31 # Updating a value my_hash.delete("city") # Deleting a pair ``` **5. Hash Methods** Introduce common hash methods: ```ruby= # keys: Retrieve all keys in a hash. my_hash.keys # values: Retrieve all values in a hash. my_hash.values # key? (or has_key?): Check if a key exists in the hash. my_hash.key?(:age) my_hash.has_key?(:age) # value? (or has_value?): Check if a value exists in the hash. my_hash.value?(31) my_hash.has_value?(31) ``` **6. Iterating Over Hashes** Show how to iterate over hash key-value pairs using each: ```ruby= my_hash.each do |key, value| puts "#{key}: #{value}" end ``` **7. Nested Hashes** Explain that hashes can be nested within other hashes, allowing for more complex data structures: ```ruby= user = { name: "Alice", contact: { email: "alice@example.com", phone: "123-456-7890" } } ``` ```ruby= numbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] student_one = ["John Doe", 20, "Mathematics"] student_two = ["Jane Smith", 22, "Mathematics"] student_three = ["Alex Johnson", 19, "Mathematics"] student_records = [student_one, student_two, student_three] puts student_records[0][0] puts student_records[1][2] puts student_records[2][1] student_records = [{name: "John Doe", score: 20,subject: 'Mathematics' , {name: "Jane Smith", score: 22,subject: 'Mathematics' }, {name: "Alex Johnson", score: 19,subject: 'Mathematics' }] ``` # Day 3 ### If else ```ruby if condition # code here else # code here end ``` ### Comparison Operators Comparison operators are tools we use in programming to compare values and make decisions based on those comparisons. In Ruby, there are several comparison operators that allow you to compare values and determine relationships between them. Here are the most commonly used comparison operators in Ruby: Equal to **(==)**: Compares if two values are equal and returns true if they are, and false otherwise. It checks for value equality, not object identity. Not equal to **(!=)**: Returns true if the values are not equal, and false if they are equal. Greater than **(>)**: Returns true if the left-hand side value is greater than the right-hand side value, and false otherwise. Less than **(<)**: Returns true if the left-hand side value is less than the right-hand side value, and false otherwise. Greater than or equal to **(>=)**: Returns true if the left-hand side value is greater than or equal to the right-hand side value, and false otherwise. Less than or equal to **(<=)**: Returns true if the left-hand side value is less than or equal to the right-hand side value, and false otherwise. ```ruby= x = 5 y = 10 puts x == y # false puts x != y # true puts x > y # false puts x < y # true puts x >= y # false puts x <= y # true puts x <=> y # -1 0 1 ``` ## Conditions ### IF conditions ```ruby= x = 5 if x > 0 puts "x is positive" end temperature = 25 if temperature > 30 puts "It's hot outside" end name = "Alice" if name == "Alice" puts "Hello, Alice!" end age = 25 if age >= 18 puts "You are eligible to vote." end ``` ### IF ELSE conditions ```ruby= age = 17 if age >= 18 puts "You are eligible to vote." else puts "You are not eligible to vote yet." end number = 10 if number.even? puts "The number is even." else puts "The number is odd." end grade = 80 if grade >= 90 puts "You got an A." else puts "You did not get an A." end ``` ```ruby= day = "Monday" if day == "Monday" puts "It's the start of the weekdays." elsif day == "Friday" puts "It's the end of the weekdays." else puts "It's a regular day." end number = 7 if number < 0 puts "The number is negative." elsif number > 0 puts "The number is positive." else puts "The number is zero." end score = 75 if score >= 90 puts "You got an A." elsif score >= 80 puts "You got a B." else puts "You got a C or below." end ``` ```ruby= x = 10 unless x > 5 puts "x is not greater than 5" end name = "" unless name.empty? puts "Name is not empty." end age = 15 unless age >= 18 puts "You are not old enough to drive." end ``` Case statement ```ruby= fruit = "apple" case fruit when "apple" puts "It's an apple." when "banana" puts "It's a banana." else puts "It's something else." end day = "Sunday" 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 language = "Ruby" case language.downcase when "ruby" puts "You are a Ruby developer." when "python" puts "You are a Python developer." else puts "You are a developer of another language." end ``` ```ruby= grade = 85 if grade >= 90 puts "A" elsif grade >= 80 puts "B" elsif grade >= 70 puts "C" else puts "D" end ``` "And" Operator (&&): The "and" operator (&&) returns true if both of its operands are true, and false otherwise. ```ruby= puts true && true # Output: true puts true && false # Output: false puts false && true # Output: false puts false && false # Output: false ``` ### AND examples ```ruby= number = 42 if number > 0 && number.even? && number < 100 puts "The number is a positive even number less than 100." end age = 25 has_license = true is_disqualified = false if age >= 18 && has_license && !is_disqualified puts "The person is eligible to drive." end ``` "Or" Operator (`||`): The "or" operator (||) returns true if at least one of its operands is true, and false if both operands are false. ```ruby= puts true || true # Output: true puts true || false # Output: true puts false || true # Output: true puts false || false # Output: false ``` ### OR examples ```ruby= number = 120 if number % 2 == 0 || number % 3 == 0 || number > 100 puts "The number meets at least one of the conditions." end fruit = "banana" if fruit == "apple" || fruit == "banana" || fruit == "orange" puts "The fruit matches one of the options." end education_level = "bachelor's degree" if education_level == "high school diploma" || education_level == "bachelor's degree" || education_level == "master's degree" puts "The person has achieved one of the education levels." end ``` "Not" Operator (!): The "not" operator (!) is used to reverse the logical value of its operand. It returns true if the operand is false, and false if the operand is true. ```ruby= puts !true # Output: false puts !false # Output: true ``` ### More Conditions ```ruby= attendance_status = 'present' arrival_time = '08:00' if attendance_status == 'present' if arrival_time <= '08:30' puts "Student is punctual." elsif arrival_time > '08:30' && arrival_time <= '09:00' puts "Student is late." else puts "Student is absent." end elsif attendance_status == 'absent' puts "Student is absent." else puts "Invalid attendance status." end ``` ```ruby= weather_forecast = 'rainy' temperature = 30 if weather_forecast == 'rainy' puts "It is rainy." if temperature > 20 puts "It is also warm. Take an umbrella and dress lightly." else puts "It is cool. Take an umbrella and dress warmly." end elsif weather_forecast == 'sunny' puts "It is sunny." if temperature > 30 puts "It is very hot. Wear sunscreen and stay hydrated." else puts "It is warm. Wear sunscreen and enjoy the sunshine." end else puts "The weather is neither rainy nor sunny. Check again later." end ``` # Day 4 ## Iteration The times method in Ruby is an iterator that allows you to execute a block of code a specified number of times. It is commonly used when you need to repeat a certain operation or action a specific number of iterations. The times method is called on an integer and takes a block of code as its argument. The block is executed repeatedly for the number of times specified by the integer. Here's an example that demonstrates the usage of the times method: ```ruby= 5.times do |index| puts "Iteration #{index + 1}" end ``` The each method in Ruby is an iterator that allows you to iterate over elements in a collection, such as an array or a hash, and perform a certain action on each element ```ruby= fruits = ['apple', 'banana', 'orange'] fruits.each do |fruit| puts "I love #{fruit}" end ``` In Ruby, the for loop is another way to iterate over a collection of elements. It allows you to loop through a range or an enumerable object, such as an array or a hash, and perform a specific action on each element. ```ruby= fruits = ['apple', 'banana', 'orange'] for fruit in fruits do puts "I love #{fruit}" end ``` The while loop is a control flow statement in Ruby that repeatedly executes a block of code as long as a specified condition evaluates to true. It is used when you want to continue executing a certain action until a specific condition becomes false. ```ruby= fruits = ['apple', 'banana', 'orange'] index = 0 while index < fruits.length do puts "I love #{fruits[index]}" index += 1 end ``` ```ruby= fruits = ['apple', 'banana', 'orange'] index = 0 until index >= fruits.length do puts "I love #{fruits[index]}" index += 1 end ``` ### MORE EXAMPLES ```ruby= array = [1, 2, 3, 4, 5] modified_array = array.map do |item| if item > 2 item * 2 else item end end array = [1, 2, 3, 4, 5] selected_items = array.select { |item| item % 3 == 0 } selected_items.each do |item| puts item end numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] numbers.each do |num| if num.even? puts "#{num} is even" elsif num.odd? puts "#{num} is odd" else puts "#{num} is neither even nor odd" end end people = [ { name: "Alice", age: 30, gender: "female", occupation: "engineer" }, { name: "Bob", age: 35, gender: "male", occupation: "teacher" }, { name: "Charlie", age: 25, gender: "male", occupation: "artist" } ] people.each do |person| if person[:age] > 30 puts "#{person[:name]} is over 30 years old" elsif person[:age] < 30 puts "#{person[:name]} is under 30 years old" else puts "#{person[:name]} is exactly 30 years old" end end people = [ { name: "Alice", age: 30, gender: "female", occupation: "engineer" }, { name: "Bob", age: 85, gender: "male", occupation: "teacher" }, { name: "Charlie", age: 70, gender: "male", occupation: "artist" }, { name: "Diana", age: 90, gender: "female", occupation: "retired" } ] people_over_80 = [] people.each do |person| if person[:age] > 80 people_over_80 << person end end puts "People over 80 years old:" people_over_80.each do |person| puts "#{person[:name]} (Age: #{person[:age]})" end group_of_numbers = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] group_of_numbers.each do |numbers| numbers.each do |number| if number.even? puts "#{number} is even" else puts "#{number} is odd" end end end ``` ## Methods # DAY 5 ```ruby= class Car end car = Car.new ``` ```ruby= class Car def initialize(color, model, year) @speed = 0 @color = color @model = model @year = year end def details { color: @color, model: @model, year: @year } end def accelerate @speed += 10 end def brake @speed -= 5 end def current_speed @speed end end ``` ```ruby= class Car def initialize(color, model, year) @color = color @model = model @year = year end def color @color end def color=(new_color) @color = new_color end def change_color @color = %w[yellow red black green violet].sample end end car = Car.new('blue', 'toyota', '1997') car.color car.change_color car.color ``` ```ruby class Car attr_accessor :brand, :model, :year, :color def initialize(brand, model, year, color) @brand = brand @model = model @year = year @color = color end def start puts "#{@brand} #{@model} started." end def stop puts "#{@brand} #{@model} stopped." end end class ElectricCar < Car attr_accessor :battery_capacity def initialize(brand, model, year, color, battery_capacity) super(brand, model, year, color) @battery_capacity = battery_capacity end def charge puts "Charging #{@brand} #{@model} with #{@battery_capacity} kWh battery." end end class GasolineCar < Car attr_accessor :fuel_capacity def initialize(brand, model, year, color, fuel_capacity) super(brand, model, year, color) @fuel_capacity = fuel_capacity end def refuel puts "Refueling #{@brand} #{@model} with #{@fuel_capacity} gallon fuel tank." end end # Creating instances of different types of cars electric_car = ElectricCar.new("Tesla", "Model S", 2023, "Red", 100) gasoline_car = GasolineCar.new("Toyota", "Camry", 2024, "Blue", 15) # Using methods inherited from the base class electric_car.start electric_car.charge electric_car.stop gasoline_car.start gasoline_car.refuel gasoline_car.stop ```