Skip to content

Instantly share code, notes, and snippets.

@Haumer
Last active July 11, 2020 22:25
Show Gist options
  • Select an option

  • Save Haumer/b512fa8d0a198800db2d8bb7e4e869ee to your computer and use it in GitHub Desktop.

Select an option

Save Haumer/b512fa8d0a198800db2d8bb7e4e869ee to your computer and use it in GitHub Desktop.
# Q6 - Complete the following code to compute the exact average of students
# grades (using each ).
grades = [19, 8, 11, 15, 13]
sum = 0
# 1) with .each
grades.each { |grade| sum += grade }
p sum.to_f / grades.size
# 2) with .sum
p grades.sum.to_f / grades.size
# 3) with .reduce(:+)
p grades.reduce(:+).to_f / grades.size
# ==============================================================================
# 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?
# 1) How do I make an array of hashes? (using .map)
students = [
['john', 28],
['mary', 25],
['paul', 21]
]
hashed_students = students.map do |student_info|
{
name: student_info[0],
age: student_info[1]
}
end
p hashed_students
# Result:
# [
# { :name => 'john', :age => 28 },
# { :name => 'mary', :age => 25 },
# { :name => 'paul', :age => 21 }
# ]
# 2) How do I convert an array into one hash:
hashed_students = {}
students.each do |student_info|
hashed_students[student_info[0]] = student_info[1]
end
p hashed_students
# Result:
# { "john" => 28, "mary" => 25, "paul" => 21 }
# 3) Super fancy way of converting and array of arrays into a hash
p students.to_h
# Result:
# { "john" => 28, "mary" => 25, "paul" => 21 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment