Ruby Part 4

Ruby Enumerables

Introduction

def iterate_colors(colors)
    array = []
    colors.each do |colors|
        array.push(colors)
    end
end

Each with Index

def skip_animals(animals, skip)
    arr = []
    animals.each_with_index do |item, index|
        arr.push("#{index}:#{item}") if index >= skip
    end
    return arr
end

Collect

def rot13(secret_messages)
    secret = []
    secret_messages.collect { |secret| 
        secret.tr!("abcdefghijklmnopqrstuvwxyz",
        "nopqrstuvwxyzabcdefghijklm") 
    }
end

Reduce

def sum_terms(n)
    terms = []
    1.upto(n) do |sum|
        terms.push(sum ** 2 + 1)
    end
    terms.reduce(0, :+)
end

Any, All, None, Find

def func_any(hash)
    hash.any? { |key, value| key.is_a? Integer }
end

def func_all(hash)
    hash.all? { |key, value| 
        value.is_a? Integer 
        and value < 10 
    }
end

def func_none(hash)
    hash.none? { |key, value| value.nil? }
end

def func_find(hash)
    hash.find { |key, value|
        key.is_a? Integer 
        and value.is_a? Integer 
        and value < 20 
    }
    hash.find { |key, value| 
        key.is_a? String 
        and value.is_a? String 
        and value[0] === "a" 
    }
end

Group_by

def group_by_marks(marks, n)
    hash = Hash.new
    marks.group_by do |name, mark|
        if mark < n
            hash.store(name, "Failed")
        elsif mark >= n
            hash.store(name, "Passed")
        end
    end
end

Jenny Plunkett

Applications Engineer @ Arm