Methods Flashcards
.gsub!
Global Substitution
example_string.gsub!(/x/, “y”)
.include?
Evaluates to true if it finds what it’s looking for and false otherwise.
string interpolation
example_string = "Andy" print "Hello, my name is #{example_string}" # ==> "Hello, my name is Andy"
while
loop method
example:
i = 1
while i
until
loop method
a complement to the while loop method.
a condition is set in a ‘until loop’ that breaks the loop
example: i = 0 until i == 6 i += 1 end
assignment operators
+= , -= , *= , /= ,
example:
example_variable += 1
You’re telling Ruby: “Add 1 to ‘example_variable’, then assign that new value back to ‘example_variable’.” This provides a succinct way of updating variable values in our programs.
for
loop method for when you do know how many times you’ll be looping
example:
for example_variable in 1…10
Inclusive and Exclusive Ranges
You saw a bit of new syntax in the previous exercise:
for num in 1…10
What this says to Ruby is: “For the variable num in the range 1 to 10, do the following.” The following was to print “#{num}”, so as num took on the values of 1 to 9, one at a time, those values were printed to the console.
The reason Ruby counted to 9 and not 10 was because we used three dots in the range; this tells Ruby to exclude the final number in the count: for num in 1…10 means “go up to but don’t include 10.” If we use two dots, this tells Ruby to include the highest number in the range.
iterator
A Ruby method that repeatedly invokes a block of code. The code block is just the bit that contains the instructions to be repeated.
The simplest iterator is the ‘loop’ method.
{}
do (to open the block)
example: i = 0 loop do i += 1 print "#{i}" break if i > 5 end
end
to close the block
example: i = 0 loop do i += 1 print "#{i}" break if i > 5 end
break
breaks a loop as soon as its condition is met.
example: i = 0 loop do i += 1 print "#{i}" break if i > 5 end
next
can be used to skip over certain steps in the loop.
example: for i in 1..5 next if i % 2 == 0 print i end
- In the above example, we loop through the range of 1 through 5, assigning each number to i in turn.
- If the remainder of i / 2 is zero, we go to the next iteration of the loop.
- Then we print the value of i. This line only prints out 1, 3, and 5 because of the previous line.
array
a method where we can store multiple numbers or objects in a variable.
example:
my_array = [1, 2, 3, 4, 5]
.each
A method which can apply an expression to each element of an object, one at a time. The syntax looks like this:
object. each do |item| # Do something
- The variable name between | | can be anything you like: it’s just a placeholder for each element of the object you’re using .each on.