Skip to content

Instantly share code, notes, and snippets.

@timkellogg
Last active August 29, 2015 14:20

Revisions

  1. timkellogg revised this gist May 9, 2015. 1 changed file with 41 additions and 0 deletions.
    41 changes: 41 additions & 0 deletions loops.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    # Making loops in many ways

    list = [1,2,3,4,5,6,7,8,9,10]

    # each loop
    sum = 0
    list.each { |num| sum+=num }
    puts "Each: #{sum}"

    # while loop
    sum = 0
    index = 0
    while list.length > index
    value = list[index]
    sum += value
    index += 1
    end
    puts "While: #{sum}"

    # for loop
    sum = 0
    for i in list do
    sum += i
    end
    puts "For: #{sum}"

    # loop
    sum = 0
    list.length.times { |num| sum += num }
    puts "Loop: #{sum}"

    # until
    sum = 0
    index = 0
    until index = list.length
    value = list[index]
    sum += value
    index += 1
    end

    puts "Until: #{until}"
  2. timkellogg renamed this gist May 9, 2015. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  3. timkellogg created this gist May 9, 2015.
    14 changes: 14 additions & 0 deletions Fibonacci.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,14 @@
    puts "Enter a number you want to calculate up to in the Fibonacci sequence"
    max = gets.chomp

    #Fibonacci
    sequence = []
    0.upto(max.to_i) do |num|
    if num > 2
    what_to_push = sequence[num - 1] + sequence[num - 2]
    sequence << what_to_push
    else
    sequence << num
    end
    end
    puts "#{sequence}"
    15 changes: 15 additions & 0 deletions Fizzbuzz
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,15 @@
    Fizzbuzz game
    puts "Please enter a number you want to fizzbuzz up to"
    user_input = gets.chomp

    1.upto(user_input.to_i) do |num|
    if num % 15 == 0
    puts "FizzBuzz"
    elsif num % 3 == 0
    puts "Fizz"
    elsif num % 5 == 0
    puts "Buzz"
    else
    puts num
    end
    end