Looping with Ruby Flashcards
The ‘While’ Loop
The while loop executes while the condition is true. Syntax: while [condition] do (do is optional) code end Example: while a < 10 print a a += 1 end
https://launchschool.com/books/ruby/read/loops_iterators#forloops
The ‘Until’ Loop
The until loop executes while a condition is false (until is becomes true Syntax: until conditional code end Example: until a == 10 print a a += 1 end
The ‘For’ Loop
The for loop is used to loop over a defined collection of elements (i.e. each value in a series or in an array) Syntax: for [new variable] in [some collection of elements] code end Examples: x = [1, 2, 3, 4, 5] for i in x do puts i end
for num in 1..15
puts num
end
Inclusive and Exclusive Ranges
A Range represents an interval—a set of values with a beginning and an end.
An Inclusive Range uses two dots (..) and includes the last element, e.g. 1..5 => 1, 2, 3, 4, 5
An Exclusive Range uses three dots (…) and excludes the last element, e.g. 1…5 => 1, 2, 3, 4
The ‘Loop’ (Break) Loop
i = 20 loop do i -= 1 print "#{i}" break if i <= 0 end
=> 191817161514131211109876543210
Next statement
The next keyword (reserved word) can be used to skip over certain steps in the loop. If you place the next reserved word in a loop, it will jump from that line to the next loop iteration without executing the code beneath it.
Next stmt examples; NOTE the use of END in the conditional
The examples produce the same result
for i in 0..5 if i < 2 then next end # <= focus on this end puts "Value of local variable is #{i}" end
for i in 0..5
next if i < 2
puts “Value of local variable is #{i}”
end
Iterators
Iterators are methods that naturally loop over a given set of data and allow you to operate on each element in the collection.
Types: Each,
The .each Iterator
The .each method, which can apply an expression to each element of an object (such as an range, hash, or an array), one at a time. Syntax and example below: object.each do | variable_name | # Do something end
array = [1,2,3,4,5] array.each do |x| x += 10 print "#{x}" end
The .times iterator
it can perform a task on each item in an object a specified number of times. Syntax and Example
t.times do |variable_name| #variable not required # code to be execute end
5.times do
puts “Hello”
end
The .split Method
Takes in a string and returns an array. If we pass it a bit of text in parentheses, .split will divide the string wherever it sees that bit of text, called a delimiter. For example:
text.split(“,”) # splits the text at the commas