Ruby Basics, Numbers, and Strings - dummies

Ruby Basics, Numbers, and Strings

By Christopher Haupt

Part of Ruby For Kids For Dummies Cheat Sheet

To get started with Ruby, you really only need to install Ruby itself and use a free code editor (not a word processor!). Notepad++, Atom, TextWrangler, and others are all good code editor choices. You’ll also commonly use a terminal or console program (free with all the common operating systems).

Once Ruby is installed, there are two common ways to run Ruby programs. If you type your Ruby code in a text file and save it, you run your code from a terminal with:

$ ruby my_code.rb

If you want to test small snippets of code, use IRB (Interactive Ruby) and start typing Ruby after the prompt:

$ irb
2.1.2 :001 > 

When testing out new code, you can easily print out the results of a calculation or string manipulation with the puts method:

2.1.2 :004 > puts 2.5 * 3
 => nil

Ruby provides a large number of built-in numeric and string methods.

Common numeric methods

Method Name Purpose
+, -, *, / Basic arithmetic
**2 Exponent (for example, raise to the second power)
( ) Use parentheses to adjust your math operation precedence
even? Returns true if even
odd? Returns true if odd
round Rounds to the nearest integer
upto, downto Loops up or down from number to another number

Common string methods

Method Name(s) Purpose
+, * Adds two strings together, repeat the string
length How long the string is
strip Removes leading and trailing white space
to_i Changes a string into a number
upcase,downcase Changes the case of the string
each_char Loops through the string returning each character
include? Returns true if a string is in another string
[] Returns character or substring
gsub Substitutes a new string where a pattern is found

You can use string interpolation to build up more complicated strings from content in other variables. Inside of double quotes, use the #{ } symbol to swap in the value of the enclosed variable:

2.1.2 :006 > age = "100"
 => "100"
2.1.2 :007 > name = "Rubyist"
 => "Rubyist"
2.1.2 :008 > "Hello #{name}, congrats on #{age} years!"
 => "Hello Rubyist, congrats on 100 years!"