Name for a value in memory. Retrieving values for later use.
age = 18
age # => 18
Assigning 18 to age (saying "storing" is fine, but less precise).
It's a piece of code with a name, which can receive values to use as parameters for their execution. We define them for re-usability and naming chinks of code can help with code clarity.
Q4 - Precisely describe what happens at *each line* using good vocabulary. Write a ruby comment next to the line you’re explaining using the #
.
def multiply(x, y) # define multiply, with the parameters x and y
return x * y # return the product of x and y's values
end # close the method block
puts multiply(5, 8) # calling the method multiply with arguments 5 and 8, and printing its return value with puts
Q5 - What’s the keyword if
? Give us an example of if
statements, using an age
variable storing a student’s age for instance.
# if starts a conditional statement (controls the flow of the code)
age = 18
puts "You can vote if" if age > 18
grades = [19, 8, 11, 15, 13]
sum = 0
grades.each do |grade|
# grade => 19
sum += grade
end
sum.to_f / grades.size # sum
# ====== OR ======
grades.sum.to_f / grades.size #sum
Q7 - Define a capitalize_name
method which takes first_name
and last_name
as parameters and returns the well-formatted fullname (with capitalized first and last names).
def capitalize_name(first_name, last_name)
"#{first_name.capitalize} #{second_name.capitalize}"
end
Concatenation joins two different string (usually with just a +) together. Interpolation allows us to run code inside a string.
"Name" + "Other name" # concatenation
"2 + 2 = #{2 + 2}" # interpolation
fruits = ["banana", "peach", "watermelon", "orange"]
# Print out "peach" from the fruits array in the terminal
print fruits[1]
# Add an "apple" to the fruits array
fruits << "apple"
# Replace "watermelon" by "pear"
fruits[2] = "pear"
# Delete "orange"
fruits.delete_at(3)
fruits.delete_at(-2)
city = { name: "Paris", population: 2000000 }
# Print out the name of the city
print city[:name]
# Add the Eiffel Tower to city with the `:monument` key
city[:monument] = "Eiffel Tower"
# Update the population to 2000001
city[:population] = 2_000_001
# city[:population] += 1
# What will the following code return?
city[:mayor] # => nil
Q11 - Use the map
iterator to convert the variable students
, an array of arrays, into an array of hashes. Those hashes should have two keys: :name
and :age
. What is the type of those keys?
students = [ [ "john", 28 ], [ "mary", 25 ], [ "paul", 21 ] ]
students.map do |student_arr|
# 0 1
# student_arr => [ "john", 28 ]
name = student_arr[0]
age = student_arr[1]
{ name: name, age: age }
end