2023-04-19 - Conditionals and Arrays

main topics


main takeaways from each challenge

Simple looping

my code

# create an array from a a Range
array = (min..max).to_a

# iterate over an array
# NOTE: bad style!
for number in array
  # do something with number
end

Sorting the wagon

my code

# sort an array of strings, case insensitive
# inspiration: https://stackoverflow.com/a/17799952
sorted_students = students.sort_by do |name|
  name.downcase
end

# get the last_student and remove
# it from the original list
last_student = students.slice!(-1)

# put the students from the array in
# a string, separating the names with ', '
# and then add the last one with ' and '
puts "#{sorted_students.join(', ')} and #{last_student}"

Black Jack

my code

# idiomatic way to check if a string
# equals to 'y' or 'yes'
['y', 'yes'].include?(answer)

Destructive methods (Horse Race)

my code

# iterate over an array having access
# to each element and its respective index
race_array.each_with_index do |horse, i|
  race_array[i] = "#{i + 1}-#{horse}!"
end