Excel Icon

RUBY BASICS 2

Links


    // ARRAYS
    friends = Array.new #with no values yet
    friends = Array["Kevin", "Karen", "Oscar", 25, true]
    puts friends 
    puts friends[0]
    puts friends[-1] # Stars counting from the end
    puts friends[0,2] # Grabs 0 and 1, not position 2
    friends[1] = "Dwight"

    # METHODS
    friends.length()
    friends.include? "Karen" #checks if a value is in the array, returns boolean
    friends.reverse()
    friends.sort() #the data types should be the same, cannot be used in an array with integers and strings


    // HASHES
    Type of data structure, similar to arrays. Store multiple pieces of info
    We can store a "key value pair" Example New York -> NY
    Key => Value You must have unique keys

    states = {
        "Pennsylvania" => "PA",
        "New York" => "NY",
        "Oregon" => "OR"
    }
    puts states
    puts states["Oregon"] #prints OR

    You can create them also like :Pensilvania => "PA" or 1 => "PA"
    puts states[:Pensilvania]
    puts states[1]

    When creating a hash you create a list of key value pairs


    // METHODS OR FUNCTIONS

    # define the method
    def NameMethod
        puts "Hi Mark, this is your method"
    end

    # call the method
    NameMethod 

    //Parameters(param)
    def sayHi(name, age)
        puts ("Hi " + name + ", you are " + age.to_s)
    end
    sayHi(Mike, 38)

    # Default Values
    def sayHi(name="noName", age=1)
        puts ("Hi " + name + ", you are " + age.to_s)
    end
    sayHi(Mike)


    //RETURN Types A funtion returns the last value unless there is a return

    def cube(num)
        num * num * num #returns the result
    end

    def cube(num)
        return num * num * num
    end

    puts cube(2)

    def cube(num)
        return num * num * num, 70
    end

    puts cube(2)[1] #as the function returns 2 values, it returns an array