RSS Log in
 

Reading notes on looping and iteration from the sixth chapter (Control-flow techniques) of The Well-Grounded Rubyist by David A. Black.

loop method

For one line of code use curly braces:
loop { # One line of code here }
For multi-lines use do..end:
i = 0
loop do
    puts i += 1
    break if i > 9
end

Or

i = 0
loop do
    puts i += 1
    next unless i == 10
    break
end

 

while keyword

i = 0
while i < 10
    puts i += 1
end

Or

i = 0
begin
    puts i += 1
end while i < 10

Or

i = 0
puts i += 1 while i < 10

 

until keyword

i = 0
until i > 9
    puts i += 1
end

Or

i = 0
begin
    puts i += 1
end until i > 9

Or

i = 0
puts i += 1 until i > 9

 

for keyword

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in nums
    puts i
end

 

times iterator

code = ?a.ord - 1
p 10.times {puts (code += 1).chr}

The code snippets above will output: a to j AND return 10 (the number of times we’ve iterated the code block).

 

code = ?a.ord
p 10.times {|i| puts (code + i).chr}

Note that block parameters are inside vertical pipes.

 

each method

array = [1,2,3,4,5]
p array.each {|i| puts "I'm No #{i}"}

Output:

I'm No 1
I'm No 2
I'm No 3
I'm No 4
I'm No 5
[1, 2, 3, 4, 5]

 

Implementing each:

class Array
    # Extend Ruby's Array class with a custom each method:
    def test_each
        i = 0
        until i == size
            yield(self[i])
            i += 1
        end 
        self
    end
end

array = [1,2,3,4,5]
array.test_each {|num| puts "I'm No #{num}"}

 

Converting a Range to an Array

upper = 5
array = (1..upper).to_a
p array

 

map method

array = ["bill", "bob", "ben"]
p array.map {|name| name.upcase}

Output:

["BILL", "BOB", "BEN"]

 

Code block reserved names

def block_local_variable
    x = "Original x!"
    3.times do |i;x|
        x = i
        puts "x in the block is now #{x}."
    end
    puts "x after the block ended is #{x}"
end

block_local_variable

=> Use a semicolon in the block parameter list to indicate that we want to use a variable named x (the reserved name) that is local to the code block.


Comments are closed
© Copyright 2012 TheBooleanFrog Powered by: BlogEngine.NET|Credits|Subscribe via RSS

Follow

twitter linkedin linkedin rss

TheBooleanFrog

Programming sticky notes and other distractions...