Ruby memoization explained

Memoization is a technique you can use to speed up your accessor methods. It caches the results of methods that do time-consuming work, work that only needs to be done once. In Rails, you see memoization used so often that it even included a module that would memoize methods for you.

This is how Memoization works in Ruby

 > var1 ||= 12
 => 12 
 > var1 ||= 13
 => 12

another workaround

 > var2 = var2 || 14
 => 14 
 > var2 = var2 || 16
 => 14 

Something different

 > var2 = var3 || 16
NameError: undefined local variable or method `var3' for main:Object
 from (irb):5
 from /home/john/.rvm/rubies/ruby-2.2.1/bin/irb:11:in `<main>'
 > var3 = var3 || 16
 => 16

Some real world example

You’ll see this memoization pattern all the time in Ruby:

class User < ActiveRecord::Base
  def twitter_followers
    # assuming twitter_user.followers makes a network call
    @twitter_followers ||= twitter_user.followers

The ||= more or less translates to @twitter_followers = @twitter_followers || twitter_user.followers. That means that you’ll only make the network call the first time you call twitter_followers, and future calls will just return the value of the instance variable @twitter_followers.



I would like to recommend you to read this:


Git Stash made simpler :: Explained


Often, when you’ve been working on part of your project, things are in a messy state and you want to switch branches for a bit to work on something else. The problem is, you don’t want to do a commit of half-done work just so you can get back to this point later. The answer to this issue is the git stash command.

Stashing takes the dirty state of your working directory — that is, your modified tracked files and staged changes — and saves it on a stack of unfinished changes that you can reapply at any time.

Stashing Your Work

To demonstrate, you’ll go into your project and start working on a couple of files and possibly stage one of the changes. If you run git status, you can see your dirty state:

$ git stash 
Saved working directory and index state \ "WIP on master: 049d078 added the index file" HEAD is now at 049d078 added the index file (To restore them type "git stash apply")

Stash acts like stack