Ruby – Introduction

Ruby is a dynamic, reflective, object-oriented, general-purpose programming language. It was designed and developed in the mid-1990s by Yukihiro “Matz” Matsumoto in Japan.

Variables

Any plain, lowercase word is a variable in ruby. Variables may consist of letters, digits and underscores.

Example

	x , y , banana2

Variables are like nicknames, you give a nickname to something you use frequently.

	phone_price = 455.00
	total = phone_price + case_price + delivery

Numbers

The most basic type of number is an integer, a series of digits which can start with a plus or minus sign.

Example

	 1, 23 , and -10000

Commas are not allowed in numbers, but underscores are. So if you feel the need to mark your thousands so the numbers are more readable, use an underscore.

	population = 12_000_000_000

Decimal numbers are called floats in Ruby. Floats consist of numbers with a decimal place or scientific notation.

Example

3.14 , -808.08 and 12.043e-04

Strings

Strings are any sort of characters (letters, digits, punctuation) surrounded by quotes. Both single and double quotes are used to create strings.

"sealab" , '2021' , or "These comments are hilarious!"

When you enclose characters in quotes, they are stored together as a single string.

Symbols

Symbols are words that look just like variables. Again, they may contain letters, digits, or underscores. But they start with a colon.

Example

:a , :b , or :ponce_de_leon

Symbols are lightweight strings. Usually, symbols are used in situations where you need a string but you won’t be printing it to the screen.

Constants

Constants are words like variables, but constants are capitalized. If variables are the nouns of Ruby, then think of constants as the proper nouns, and most importantly cannot be changed.

Examples

Time , Array or Bunny_Lake_is_Missing

Methods

If variables and constants are the nouns, then methods are the verbs. Methods are usually attached to the end of variables and constants by a dot. You’ve already seen methods at work.


front_door.open

In the above, open is the method. It is the action, the verb. In some cases, you’ll see actions chained together.


front_door.open.close

We’ve instructed the computer to open the front door and then immediately close it.


front_door.is_open?

The above is an action as well. We’re instructing the computer to test the door to see if it’s open. The method could be called Door.test_to_see_if_its_open, but the is_open? name is succinct and just as correct. Both exclamation marks and question marks may be used in method names.

Method arguments

A method may require more information in order to perform its action. If we want the computer to paint the door, we should provide a color as well. Method arguments are attached to the end of a method. The arguments are usually surrounded by parentheses and separated by commas.

front_door.paint( 3, :red )

The above paints the front door 3 coats of red.

front_door.paint( 3, :red ).dry( 30 ).close()

The above paints the front door 3 coats of red, dries for 30 minutes, and closes the door. Even though the last method has no arguments, you can still put parentheses if you like. There is no use dragging an empty inner tube, so the parentheses are normally dropped.

Some methods (such as print) are kernel methods. These methods are used throughout Ruby. Since they are so common, you won’t use the dot.

print "See, no dot."

Class methods

Like the methods described above (also called instance methods), class methods are usually attached after variables and constants. Rather than a dot, a double colon is used.

Door::new( :oak )

As seen above, the new class method is most often used to create things.

Global variables

Variables which begin with a dollar sign are global.

Examples

$x , $1 , $chunky and $CHunKY_bACOn

Global variables can be used anywhere in your program. They never go out of sight.

Instance variables

Variables which begin with an at symbol are instance variables

Examples

@x , @y , and @only_the_chunkiest_cut_of_bacon_I_have_ever_seen 

These variables are often used to define the attributes of something. For example, you might provide Ruby with the width of
the front_door by setting the @width variable inside that front_door. Instance variables are used to
define characteristics of a single object in Ruby.

Think of the at symbol as meaning attribute.

Class variables

Variables which begin with double at symbols are class variables.

Example

@@x , @@y , and @@i_will_take_your_chunky_bacon_and_raise_you_two 

Class variables, too, are used to define attributes. But rather than defining an attribute for a single object in Ruby, class variables give an attribute to many related objects in Ruby. If instance variables set attributes for a single front_door, then class variables set attributes for everything that is a Door.

Think of the double at prefix as meaning attribute all.

You change a class variable and not just one changes, they all change.

Blocks

Any code surrounded by curly braces is a block.

Example

	2.times { print "Yes, I've used chunky bacon in my examples, but never again!" }

With blocks, you can group a set of instructions together so that they can be passed around your program.

Block arguments

Block arguments are a set of variables surrounded by pipe characters and separated by commas.

Example

|x| , |x,y| , and |up, down, all_around| 

Block arguments are used at the beginning of a block.

{ |x,y| x + y }

In the above example, |x,y| are the arguments. After the arguments, we have a bit of code. The expression x + y adds the two arguments together.

Ranges

A range is two values surrounded by parentheses and separated by an ellipsis (in the form of two or three dots).

(1..3) is a range, representing the numbers 1 through 3.
('a'..'z') is a range, representing a lowercase alphabet.

Normally, only two dots are used. If a third dot is used, the last value in the range is excluded.

(0...5) represents the numbers 0 through 4.

Arrays

An array is a list surrounded by square brackets and separated by commas.

[1, 2, 3] is an array of numbers.
['coat', 'mittens', 'snowboard'] is an array of strings.

Hashes

A hash is a dictionary surrounded by curly braces. Dictionaries match words with their definitions. Ruby does so with arrows made from an equals sign, followed by a greater-than sign.

{'a' => 'aardvark', 'b' => 'badger'}

Regular Expressions

A regular expression (or regexp) is a set of characters surrounded by slashes.

Examples

/ruby/ , /[0-9]+/ and /^\d{3}-\d{3}-\d{4}/

Regular expressions are used to find words or patterns in text. The slashes on each side of the expression are pins.

Operators

You’ll use the following list of operators to do math in Ruby or to compare things. Scan over the list, recognize a few. You know, addition + and subtraction – and so on.

** ! ~ * / % + - &
 << >> | ^ > >= < <= <=>
 || != =~ !~ && += -= == ===
 .. ... not and or 

Keywords

Ruby has a number of built-in words, imbued with meaning. These words cannot be used as variables or changed to suit your purposes. Some of these we’ve already discussed. They are in the safe house my friend. You touch these and you’ll be served an official syntax error.

 alias and BEGIN begin break case class def defined
 do else elsif END end ensure false for if
 in module next nil not or redo rescue retry
 return self super then true undef unless until when
 while yield 

Be first to comment

Leave a Reply