woot! easier mapping!

Say for example you have this — A table of users, with a name and a boolean value of true or false whether they are a student or not.

class CreateUsers ActiveRecord::Migration 
def change :users do |t|
t.string :name
t.boolean :student
end
end

Say you want to get count the number of users that are students. Ex: If there are 5 users, 4 students and 1 not a student:

users = User.all # 
users.map{|user| user.student} #[true, true, false, true, true] users.count(true) # 4

You can do it this way instead! Use the &: for mapping and use count(value), where in this case we want value to be true, because we are counting the number of true values.

users.map(&:student).count(true) #4

Originally published at sofiama.github.io on November 24, 2014.