Basics Flashcards
Method Structure
def exampleMethod(example1, example2) return exampleVariable end
To check length of string add
variable.length
puts
text output with newline at end
converts everything to a string
converts nil elements to empty string
returns nil
text output with no newline at end
converts everything to a string
text output of array includes brackets
returns nil
p & pp
both: text output is raw objects passed to it
both: returns the same object that was passed to it as an argument
both: good for debugging
pp: attempts to print large hashes and arrays in a more readable format
if/else/else if format
if condition1 example elsif condition2 example else example end
while loop format
while condition
example
end
declaring array
adding to array with shovel
newArray = []
newArray «_space;variable
Enumerable Iteration Methods
How to iterate through an ARRAY, no passing index
Single line method format
Multiline method format
arrayExmaple.each
Single line method for a single line of code in block:
arrayExample.each { |elementName| puts elementName }
Multiline for multiple lines of code in block:
arrayExample.each do |elementName|
puts elementName
puts “example”
end
Enumerable Iteration Methods
How to iterate through a STRING, no passing index
stringExample.each_char
stringExample.each_char |char|
puts char
end
Enumerable Iteration Methods
How to iterate through an ARRAY while passing index
arrayExmaple.each_with_index
arrayExample.each_with_index do |elementName, index|
puts elementName
puts index
end
Enumerable Iteration Methods
How to iterate through a STRING while passing index
stringExample.each_char.with_index do |char, index|
puts char
puts index
end
Enumeration refers to
Enumeration refers to traversing over objects. In Ruby, we call an object enumerable when it describes a set of items and a method to loop over each of item.
Range Enumerable
Iterate from start number to end number (inclusive)
Iterate from start number to end number (excluding end)
(start. .end).each
ex: (start..end).each { |num| puts num }
(start. ..end).each
ex: (start…end).each { |num| puts num }
Enumerable to repeat something a particular number of times
numberOfTimes.times { what to do } ex: 3.times { puts "echo" } echo echo echo