Ruby Basics


Collapse Content

Learn Ruby by going through example code and solving challenges!

For an easier version of this tutorial, see Learn Ruby for Beginners.

Everything is an Object

Everything in Ruby is an Object.

# This is a comment 
#=> Output will be shown like this

#Everything is an Object of a Class
3.class #=> Fixnum
3.0.class #=> Float
"Hello".class #=> String
'hi'.class #=> String

# Special values are objects too  
nil.class #=> NilClass
true.class #=> TrueClass
false.class #=> FalseClass

Basic arithmetic

Ruby uses the standard arithmetic operators:

1 + 1  #=> 2
10 * 2 #=> 20
35 / 5 #=> 7
10.0 / 4.0 #=> 2.5
4 % 3 #=> 1  #Modulus
2 ** 5   #=> 32 #Exponent 

Arithmetic is just syntactic sugar for calling a method on Numeric objects.

1.+(3) #=> 4
10.* 5 #=> 50

The Integer class has some integer-related functions, while the Math module contains trigonometric and other functions.

2.even? #=> true
12.gcd(8) #=> 4

Equality and Comparisons

#equality
1 == 1 #=> true
2 == 1 #=> false

# Inequality
1 != 1 #=> false
2 != 1 #=> true
!true  #=> false
!false #=> true

#Logical Operators
3>2 && 2>1 #=> true
2>3 && 2>1 #=> false
2>3 || 2>1 #=> true   

#In Ruby, you can also use words
true and false #=> false
true or false #=> true
true and not false => true

# apart from false itself, nil is the only other 'false' value    
!nil   #=> true
!false #=> true
!1     #=> false
!0     #=> false

#comparisons
1 < 10 #=> true
1 > 10 #=> false
2 <= 2 #=> true
2 >= 2 #=> true

Variables

x = 25 #=> 25
x #=> 25

# Note that assignment returns the value assigned
# This means you can do multiple assignment:    
x = y = 10 #=> 10
x #=> 10
y #=> 10

# Variables can be dynamically assigned to different types
thing = 5  #=> 5
thing = "hello" #=> "hello"
thing = true #=> true    

# By convention, use snake_case for variable names
snake_case = true

# Use descriptive variable names
path_to_project_root = '/good/name/'
path = '/bad/name/'

Challenge

What will the following code return?

true and 0 && !nil and 3 > 2

(Note: don't use such code in real programs!)

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Challenge

ab is considered powerful if (and only if) both of the following 2 conditions are met:

  1. ab >= 2 * b2
  2. ab >= (a*b)2

return true if ab is powerful and false otherwise.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Contact Us