Ruby Syntax Flashcards
How do you make a class?
class Name
attr_accessor :first, :second
def initialize(first, second) @first = first @second = second end
end
How do you make an array?
Dynamic Array:
array_name1 = []
array_name2 = Array.new()
Static Array:
array_name3 = [“One”, “Two”, “Three”]
How do you write comments?
for single line comments
= begin
for block comments
=end
How do you find the number of items in an array?
array_name.length
How do you insert a variable into a string?
“This is a #{quote}”
How do you write a while loop?
i = 0 (control variable) count = 5
while i < count
DO SOMETHING
i += 1
end
How do you write a for loop?
count = 5
for count in 0..4
DOES SOMETHING
end
How do you write an until loop?
count = 0
begin
count += 1
end until (count==6)
How do you write an each loop for arrays?
colors = [“red”, “blue”, “green”, “yellow”]
colors.each { |x| puts x}
How do you write an if statement?
if CONDITION CONSEQUENT else ALTERNATIVE end
How do you write an elsif statement?
if CONDITION 1 CONSEQUENT 1 elsif CONDITION 2 CONSEQUENT 2 else ALTERNATIVE end
How do you add items to an array?
array_name[n] = Value
array_name «_space;Value
How do you write a case statement?
count = 10
case count when 1..4 action 1 when 5 action 2 else ALTERNATIVE end
How do you access values within a multidimensional array?
2d_array = [[1, 2, 3], [4, 5, 6]]
puts 2d_array[0][1]
It will print out 2
How do you make an enumeration?
module Name
Thing1, Thing2, Thing3 = *1..3
end