<< Previous Page
    

    
      Table of Contents
    

    
      Next Page >>
    
  
04
%q{Loops}

# Recommended loop style
loop do
next if skippable?
do_something
break if enough?
redo if failed?
end

# Don't do this
for x in 1..10
puts x
end

# This is better
10.times {|x| puts x}

# Iterate over range
(2..5).each {|x| puts x}

# Iterate over range excluding last
(2...5).each {|x| puts x}

# Iterate over array
['a', 'b', 'c'].each {|x| puts x}
# a
# b
# c

# Iterate over array with index
arr = ['a', 'b', 'c']
arr.each_with_index do |x,index|
puts "#{x} #{index}"
end
# a 0
# b 1
# c 2

# Iterate with index with map
arr = ['a', 'b', 'c']
arr.each_with_index.map do |x,index|
"#{x} #{index}"
end
=> ["a 0", "b 1", "c 2"]

# Iterate over hash
{ a: 1, b: 2, c: 3 }.each {|k, v| puts k, v }

# Iterate with while
a = 0
a += 1 while a < 5

# Iterate with until
a = 5
a -= 1 until a.zero?
%q{Enumerable}

words = ["The", "Ruby", "Cheatsheet"]

words.map {|word| word.length}
=> [3, 4, 10]

words.select {|word| word.length == 4}
=> ["Ruby"]

words.reject {|word| word.length == 4}
=> ["The", "Cheatsheet"]

words.find {|word| word.length == 4}
=> "Ruby"

# Count instances of element
words.count
=> 3

words.count("Ruby")
=> 1

# Inject (AKA reduce)
words.inject(0) do |sum, word|
sum + word.length
end
=> 17

# With no argument, uses first
# element of array as initial value
words.inject do |result, word|
result.prepend(word)
end
=> "CheatsheetRubyThe"

# Partition using block condition
short, long = words.partition do |word|
word.length < 5
end

short => ["The", "Ruby"]
long => ["Cheatsheet"]

# Convert to enumerator
word_enumerator = words.each
=> #<Enumerator: ...>

word_enumerator.next
=> "The"
word_enumerator.next
=> "Ruby"
word_enumerator.next
=> "Cheatsheet"
04
    
      << Previous Page
    

    
      Table of Contents
    

    
      Next Page >>