This post was created primarily for me, and secondarily for the few people out there who are learning ruby and come from a javascript background. Here are some categorized code samples that basically do the same thing in either language. I’m using Ruby 2.0+.

Comments

// this is a single line comment

/* this is a
   multi-line comment */
# this is a single line comment

# this is a
# multi-line comment

=begin
  another way
  to do multi-line
=end

Variables

In javascript people tend to name their variables starting with a lowercase letter then camel case after that (ie thisIsMyVariable). In ruby, people tend to use all lowercase letters and underscores for separators (ex this_is_my_variable).

var myVariable = "hello there";
my_variable = "hello there"

Arrays

var arr = [1,2,3,4];

arr.push(5);

arr = arr.map(function(a) {
  return a * 2;
});
arr = [1,2,3,4]

arr.push(5)

arr.map! {|i| i * 2} # the `!` saves the result back to the variable

Hashes (objects)

var obj = {
  one: 1,
  two: 2
};

for (var key in obj) {
  // see http://bit.ly/1krXmjL for explanation
  if(obj.hasOwnProperty(key)){
    console.log(key + ': ' + obj[key]);
  }
}

obj.hasOwnProperty('one'); // true
obj = {
  one: 1,
  two: 2
}

obj.each {|key, value|
  puts "#{key}: #{value}"
}

obj.has_key? # true

Functions

function multiply(a, b) {
  return a * b;
}

function addOne(a) {
  return (a || 0) + 1;
}

console.log(multiply(5,10)) // 50

console.log(addOne())       // 1
console.log(addOne(5))      // 6
def multiply(a, b)
  return a * b
end

def add_one(a = 0)
  return a + 1
end

puts multiply(5,10)  # 50
puts multiply 5,10   # 50

puts add_one         # 1
puts add_one 5       # 6

Classes

function Car(year, brand) {
  this.year = year;
  this.brand = brand;
}

Car.prototype.dispayInfo = function() {
  return this.year + ' ' + this.brand;
};

var civic = new Car(2005, 'honda');
civic.dispayInfo(); // 2005 honda
class Car
  attr_accessor :year, :brand

  def initialize(year, brand)
    @year = year
    @brand = brand
  end

  def display_info
    "#{year} #{brand}"
  end
end

honda = Car.new(2005, 'honda')
honda.display_info # 2005 honda

Credits

Here’s a page this inspired some of the content of my post:

I grew up using Macs, was forced back to Windows for a job, worked on Ubuntu for a while, and now have finally landed back in the Mac realm. After having been around the block on just about every platform, I can safely argue that Mac’s are better for a developer who’s serious about Linux but doesn’t want to sacrifice a quality UI.

One of the hardest things about setting up a new box is figuring out all the quirky setup nuances that make your box shine. This post is the chronicle of my most recent, most ultimate setup yet.

This was all performed on a fresh MacBook Air, but really anything running Mavericks works.

Ingredients

  • iTerm2 replaces the stock Terminal app
  • Alfred replaces the default Mac Spotlight
  • Homebrew manages all your command line packages
  • Solarized Colors makes your command line pretty
  • Vim the best, and hardest, text editor and IDE that is worth learning if you are serious about computers
  • jVim my personal vim, and extras, setup
  • Tmux manages windows within your terminal. It lets you open up and resize several terminal windows without leaving the keyboard and reaching for that dirty mouse.
  • Zsh a better shell that is bash backwards compatible
  • Oh my zsh some nice default settings and themes for zsh

Getting Started

Installing

Start by downloading and install iTerm, Alfred, Homebrew, and Solarized (imported into iTerm2 from this file). Once you have that done, setup your iTerm2 profile to use your newly imported Solarized Dark theme. Also make sure your “Report terminal type” is set to xterm-256color. Then let’s keep going on the installation by hopping into iTerm2 and running some shizz.

Homebrew installs stuff in /usr/local/bin so let’s add it to our path by modifying ~/.bashrc and ~/.zshrc

echo “PATH=/usr/local/bin:/usr/local/sbin:$PATH" | tee ~/.bashrc ~/.zshrc

Install zsh, vim, tmux, and something to connect your Mac’s clipboard to Vim:

brew install zsh tmux vim reattach-to-user-namespace

Tell your mac to permit your custom shell:

echo “/usr/local/bin/zsh” | sudo tee -a /etc/shells

Change your default shell:

chsh -s /usr/local/bin/zsh $USER

Move a folder to account for some Mac bug:

sudo mv /etc/{zshenv,zshrc}

Install oh-my-zsh:

curl -L http://install.ohmyz.sh | sh

Install jVim to your home directory:

git clone https://github.com/jondlm/jvim.git ~/.jvim
cd ~/.jvim
git submodule update --init --recursive
./install.sh bonus

Restart iTerm2.

Install some more stuff with brew:

brew install vim tmux reattach-to-user-namespace

Fire up Tmux:

tmux

Setup vim:

vim
# ignore errors for now
:BundleInstall

Interlude…

To be honest, I started writing this article several months ago and never finished it. I suspect these steps are correct, but your mileage may vary.

Fin.

Linux is hard. Really hard. I didn’t start getting good at it until I started writing everything I learned down. Maybe this stuff will help someone else.

Terminal

  • ctrl-u delete all left of the cursor
  • ctrl-k delete all right of the cursor
  • ctrl-w delete word left of the cursor
  • ctrl-y paste
  • ctrl-l clear
  • watch -n 2 date run the date command every 2 seconds and show the results as they happen fullscreen
  • tput colors display number of colors your terminal supports
  • echo $TERM shows what terminal you are using
  • watch -n 2 "dmesg | tail -30" continually watch the kernel messages for debugging

Recording sessions

  • script terminal_session.txt starts recording all the output from your terminal to a file
  • ctrl-d ends the recording session
  • less -R terminal_session.txt displays the session in its “raw” form for coloring, etc.

File system

  • mv {,new.}somefile.txt moves somefile.txt to new.somefile.txt using a bash feature called “brace expansion”
  • df -ah shows all your mounted disks and their free space
  • df -ih shows your inode information, can be useful when processes aren’t releasing files properly
  • du -sh * shows the file sizes for all files and folders in the current folder
  • tail -f shows the tail of a file and “follows” and outputs any changes made to that file
  • mv ~/Linux/Old/!(Tux.png|Tux2.png) ~/Linux/New/ move all files except one
  • tree shows current directory as tree (usually doesn’t come with stock OS)
  • tree -H http://jondelamotte.com outputs an HTML tree of a site with a base href
  • pushd . pushes your current directory into a temporary array
  • pushd switch between current director and the one on the top of your stack, like alt-tab on windows
  • popd recalls the last stored directory and sends you there
  • diff folder1 folder2 -q runs a diff on two folds and gives the brief differences
  • diff file1 file2 diff two files
  • chmod g+rw srv add read and write permissions for the group to the srv folder
  • chmod 600 file grant read and write privileges to the file owner
  • chmod 666 file grant read and write privileges to the owner, the group, and everyone
  • chmod 777 some_dir when chmodding a directory, make sure you use 7 instead of 6, execute on a directory doesn’t mean the same thing as a file

Archiving and compression

  • tar -zcvf test.tar.gz /home/jon/test create a compressed archive and store it to a new file called test.tar.gz
  • tar -xvf test.tar.gz uncompress and extract an existing archive
  • tar -zcvf test.tar.gz -C /home/jon/test . create a compress archive without an extra folder in it

Finding stuff

Search the root directory for anything with ‘something’ in it and pipe that to less:

  • find / -name 'something' | less
  • find / -iname '*something*' case insensitive with wildcard matching
  • find / | grep something 2>/dev/nul another way of doing the same thing, ignore errors
  • grep -rn 'something' recursively grep through files in the current dir, show the line numbers
  • grep -rn 'something' --exclude-dir=node_modules exclude a directory from your search
  • grep -rin contact_bg ./ | cut -f 1,2 -d: case insensitive search for “contact_bg” in current directory, split the results on colons and only show the first two columns from the result, basically hide the contents of the result
  • dpkg —get-selections lists packages that are installed
  • which man or which node find where your binary is located on the file system

Networking

  • /etc/hosts is a file that is like a personal DNS. You can map custom IPs to hostnames in it.
  • sudo netstat -tulpn display all the open ports on your machine

  • ssh -i ~/.ssh/id_rsa jon@10.10.10.10 log into the 10.10.10.10 machine with the user jon using the private key file ~/.ssh/id_rsa

  • curl http://www.jondelamotte.com perform a GET to www.jondelamotte.com
  • curl -I http://jondelamotte.com perform a HEAD against jondelamotte.com, shows status and other useful info without requesting the body

User management

  • usermod -a -G youre_mobile jon add existing user to existing group
  • Check the /etc/group file for group information
  • The /etc/sudoers file let’s you map groups or users to have sudo privileges

Release and renew IP

  1. sudo dhclient -r
  2. sudo dhclient
  3. sudo ifdown eth0
  4. sudo ifup eth0

Compiling programs

  1. ./configure
  2. make
  3. sudo make install install as root

Environment Variables

  • echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile adds a folder to your path for the bash shell
  • env list out all your environment variables
  • export SOMETHING="la la la la" set an environment variable
  • unset SOMETHING remove an env variable
  • echo $SOMETHING print out an env variable

Set time zone

  1. sudo rm /etc/localtime
  2. sudo ln -s /usr/share/zoneinfo/US/Pacific /etc/localtime
  • date —iso8601=seconds -u displays iso 8601 date time for UTC. Some version of linux don’t have this flag, see below
  • date +%FT%T%z displays iso 8601 local and works with all versions of date
  • date -d '4 days ago' relative dates

Security

Generating a new ssh key

For the best security, you should be using one SSH key per device you use. An SSH key can optionally be password protected for extra security. When you generate a key, two files are created. One of the private key (don’t give it to anyone), the other is the public key, which is meant to be public.

  1. Make sure you don’t already have an ssh key you can use, check ~/.ssh
  2. ssh-keygen -t rsa -C "your_email@example.com"
  3. ssh-add ~/.ssh/id_rsa

Using ssh-add puts your private key into ssh-agent that stores your password and private key while your machine is running

Make sure your ssh-agent is running with ssh-agent bash

Distributions

  • cat /etc/*-release to figure out what distro you are running

Ubuntu unity

  • ctrl + alt + num5 hit any of the numpad numbers to align the windows
  • hold super key for keyboard shortcuts

Compilation

  • make -j16 number of threads, 2x your number of cores makes sense”

I haven’t been able to write many blog posts lately. I’ve been very busy and have lots to share, but for the time being I am going to release a series of cheat sheets I’ve been compiling for my own reference. Theses posts will continually be updated as I find more useful commands. I’ll kick the series off with Git; the best source control on the planet.

General

  • git show HEAD~5:file.txt shows a file from 5 commits ago
  • git diff HEAD^ — file.txt diff file.txt to the last commit
  • git diff master..remotes/origin/master compares local master to remote origin master
  • git diff --stat summary of changes by file and line number changes
  • git rebase -i interactively rebase your commits, for example to squash commits into one before pushing
  • git reset --hard HEAD WARNING: reset your directory to the HEAD state
  • git init initalize a repo
  • git add --all stage all changes
  • git commit -m "the first commit" commit the changes
  • git checkout master -- file.html checkout a file from another branch
  • git checkout HEAD -- file.html checkout a file from HEAD

Merge conflicts

  • git checkout --ours something.txt
  • git checkout --theirs something.txt

There are plenty of fun and quirky features in Javascript. Beginners typically have trouble with the for in statement. In most other programming languages, a for in statement lets you loop through each of the items in an array or list. Javascript won’t yell at you if you try to use for in on an array, but the result will be really weird. In javascript, for in is meant to loop through each of the properties of an object. Let’s look at a bad example, followed by a good one.

Bad

var arr = [1,2,3,4,5];
var sum = 0;

for (item in arr) { sum += item; }

console.log(sum); // "001234" // WTF?!

I won’t go into the details of why this is bad, just don’t use for in with arrays. You should be using forEach or a simple for loop instead.

Good

var jon = {
  name: 'Jon',
  age: 25
};

for (item in jon) {
  console.log(item + ' ' + jon[item]);
}   // name Jon
    // age 25

Prototype Pollution Problem

Even if you use for in correctly, you can still sometimes get unexpected results. It happens when you make changes to the prototype of an object. Let’s look at another example:

function Person(name) {
  this.name = name;
}

Person.prototype.getName = function() {
  return this.name;
};

var jon = new Person('Jon');

console.log(jon.getName()); // "Jon"

for (item in jon) {
  console.log(item + ' ' + jon[item]);
}   // name Jon
    // getName function .... // WTF?!

The latest version of javascript allows you to specify if you want a prototype method to be enumerable. I won’t go into the details of that. Rather, here is a good way to exclude prototype methods:

for (item in jon) {
  if (jon.hasOwnProperty(item))
    console.log(item + ' ' + jon[item]);
}   // name Jon