Skip to content

Instantly share code, notes, and snippets.

@todlazarov
Last active January 25, 2016 19:07
Show Gist options
  • Save todlazarov/93df9436b75e16f09c14 to your computer and use it in GitHub Desktop.
Save todlazarov/93df9436b75e16f09c14 to your computer and use it in GitHub Desktop.
# 1. We are working with a database and we need to create a comma separated list of facebook friend's IDs
users.select {|u| u.is_friend?}
.map {|u| u.facebook_id}
.compact
.join(',')
# Pseudocode
# We combine our methods by chaining them together for clarity and readibility.
# First we create a method that checks if the given user is our friend and call it "is_friend?".
# We use the select method to itterate over the users database and return an array containing
# all elements for which is_friend? returns true.
# We chain the map selector next, in order to extract only the facebook_id from each of the user's row.
# The map selector itterates over each user and returns a new a new array which is full of the facebook IDs only.
# We use the compact method next, because not all of the users would have created accounts using facebook,
# therefore there will be nils in our array.
# We finally join the array together in order to create our comma separated list.
# ========================================================
# 2. There is a big databse and there is a need to count how many of the total users are male and female.
users.map {|u| u.is_male? ? 1 : 0}
.reduce(:+)
# Pseudocode
# We create a method called "is_male?" that checks in the database if the user's male column contains the word yes.
# We use the map method to create a new array which contains either a 1 or 0, depending on whether or not the
# is_male? method returns true for each user.
# Once the array is created, we use the reduce to collector to add all the elements in the array,
# which gives us the total number of users that are male.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment