if age >= 18 puts “You are an adult.” elsif age >= 13 puts “You are a teenager.” else puts “You are a child.” end if … elsif … else … end is used for decision making. Output:
puts fruits[0] # apple puts fruits.length # 3 fruits << “mango” # Add new element puts fruits.inspect # Show complete array Arrays store multiple values.
The Ruby Cheatsheet provides the fundamentals of Ruby programming. It helps students and developers to build the projects and prepare for the interviews. Go through the cheat sheet and learn the concepts. Thus, this improves the coding skills.
Basic Syntax
Variables
Operators
Comments
String
String Interpolation
If-else Statement
Classes and Objects
Break Statements
Ruby Blocks
Modules
Array
Hashes
Ranges
Regular Expression
Exception Handling
Commonly Used Library
1. Basic Syntax
This is the basic syntax of the Ruby programming language that displays the text using puts and print.
puts "Hello, World!"
print "Tutorialspoint!"
2. Variables
Variables are used for the memory location. Ruby supports various types of variable −
# Defining the variables
x =10# integer
y =20.5# float
puts x + y
3. Operators
The operators are the symbol that tells the compiler to perform logical tasks.
Operators
Description
Example
Arithmetic Operators
This is basic mathematical operations.
‘a + b’, ‘a – b’, ‘a * b’, ‘a / b’, ‘a % b’
Relational Operators
This compares two values.
‘a == b’, ‘a != b’, ‘a > b’, ‘a < b’, ‘a >= b’, ‘a <= b’
Logical Operators
This combine the conditional statements.
‘a && b’, ‘a || b’, ‘!a’
Bitwise Operators
This perform in the bit level.
‘a & b’, ‘a | b’, ‘a ^ b’, ‘~a’, ‘a << b’, ‘a >> b’
Assignment Operators
This assign the values to the variables.
‘a = b’, ‘a += b’, ‘a -= b’, ‘a *= b’, ‘a /= b’, ‘a %= b’
Below are the some examples of operators in Ruby programming language −
# Arithmetic Operators# Addition
puts 8+18# Subtraction
puts 9-3# Multiplication
puts 7*6# Division
puts 20/4# Comparison Operators# Greater than
puts 10>5# Equal to
puts 10==5# Not equal to
puts 10!=5
4. Comments
Comments are used to show the information. The single-line comment is denoted by “#” whereas multi-line comments are written using the =begin and =end keywords.
# This is a single-line comment=begin
multi-line comment
=end
5. String
The strings are used to print the text. In Ruby, strings are represented using both single and double quotes.
The string interpolation is the process of inserting the values with the help of expression inside the curly braces #{}.
name ="Tutorialspoint!"
puts "Welcome to #{name}!"
7. If-else Statement
The if-else statement is a part of the control structure used to execute the logic conditionally, based on whether the condition is true or false.
age =18if age >=18
print "You are eligible for vote."else
print "You are are not eligible for vote."end
8. Classes and Objects
Classes and objects are fundamental concepts of object-oriented programming. A class defines the blueprint for an object, whereas an object is an instance of a class.
classPersondefinitialize(name, id)@name= name
@id= id
enddeffun
puts "My name is #{@name} and I am #{@id} years old."endend
person =Person.new("Sanjay",25)
person.fun
9. break Statements
In Ruby, the break statement terminates the program loop.
num =[1,2,3,4,5,6,7,8,9,10]
num.eachdo|num|if num ==7
puts "The loop break at the number #{num}"breakend
puts "The processing number is #{num}"end
puts "Loop ended."
10. Ruby Blocks
The blocks represent the anonymous function in Ruby that is passed into the methods. The block can be declared using a single-line or multi-line block.
times { puts "Hello, Block!"}
11. Modules
In Ruby, a module is a collection of methods and constants that can be used to organize and structure code.
# example of modulesmoduleMathHelpersdefsquare(x)
x * x
endendincludeMathHelpers
puts square(4)
12. Array
In Ruby, an array defines the ordered, indexed collection of objects. The object holds the data types such as String, Integer, Fixnum, Hash, Symbol, and even other Array objects.
arr =[10,20,30,40,50]
arr.each{|i| puts i }
13. Hashes
The hashes are similar to dictionaries by defining key−value pairs.
hash ={ name:"Ruby", id:3323}
puts hash[:name]
14. Ranges
The ranges are data types that show a sequence of values.
(1..5).each{|i| puts i }
15. Regular Expression
Regular Expression is defined by the special sequence of characters that help users to find the set of string matches or particular syntax held in the program.
/pattern//pattern/im# option can be specified%r!/usr/local!# general delimited regular expression
16. Exception Handling
In Ruby, an exception handling is the process of handling the error raised in the program. These errors occur during the execution of the program. In simple, unexpected, or unwanted events.
beginraise# block where exception raiserescue# block where exception rescueend
17. Commonly Used Library
Here, we are providing the example of the JSON library.
require'json'
data ={ name:"Ruby", type:"Programming Language"}
puts JSON.generate(data)
The standard Ruby distribution contains useful tools along with the interpreter and standard libraries −
These tools help you debug and improve your Ruby programs without spending much effort. This tutorial will give you a very good start with these tools.
RubyGems −RubyGems is a package utility for Ruby, which installs Ruby software packages and keeps them up-to-date.
Ruby Debugger −To help deal with bugs, the standard distribution of Ruby includes a debugger. This is very similar to gdb utility, which can be used to debug complex programs.
Interactive Ruby (irb) −irb (Interactive Ruby) was developed by Keiju Ishitsuka. It allows you to enter commands at the prompt and have the interpreter respond as if you were executing a program. irb is useful to experiment with or to explore Ruby.
Ruby Profiler −Ruby profiler helps you to improve the performance of a slow program by finding the bottleneck.
Additional Ruby Tools
There are other useful tools that don’t come bundled with the Ruby standard distribution. However, you do need to install them yourself.
eRuby: Embeded Ruby −eRuby stands for embedded Ruby. It’s a tool that embeds fragments of Ruby code in other files, such as HTML files similar to ASP, JSP and PHP.
ri: Ruby Interactive Reference −When you have a question about the behavior of a certain method, you can invoke ri to read the brief explanation of the method.
For more information on Ruby tool and resources, have a look at Ruby Useful Resources.