The syntax of the Ruby programming language is broadly similar to that of Perl and Python. Class and method definitions are signaled by keywords, whereas code blocks can be defined by either keywords or braces. In contrast to Perl, variables are not obligatorily prefixed with a sigil. When used, the sigil changes the semantics of scope of the variable. For practical purposes there is no distinction between expressions and statements. Line breaks are significant and taken as the end of a statement; a semicolon may be equivalently used. Unlike Python, indentation is not significant.

One of the differences from Python and Perl is that Ruby keeps all of its instance variables completely private to the class and only exposes them through accessor methods (attr_writer, attr_reader, etc.). Unlike the "getter" and "setter" methods of other languages like C++ or Java, accessor methods in Ruby can be created with a single line of code via metaprogramming; however, accessor methods can also be created in the traditional fashion of C++ and Java. As invocation of these methods does not require the use of parentheses, it is trivial to change an instance variable into a full function without modifying a single line of calling code or having to do any refactoring achieving similar functionality to C# and VB.NET property members.

Ruby syntax

Python's property descriptors are similar, but come with a trade-off in the development process. If one begins in Python by using a publicly exposed instance variable, and later changes the implementation to use a private instance variable exposed through a property descriptor, code internal to the class may need to be adjusted to use the private variable rather than the public property. Ruby's design forces all instance variables to be private, but also provides a simple way to declare set and get methods. This is in keeping with the idea that in Ruby one never directly accesses the internal members of a class from outside the class; rather, one passes a message to the class and receives a response.

Ruby syntax

Interactive sessions

The following examples can be run in a Ruby shell such as Interactive Ruby Shell, or saved in a file and run from the command line by typing ruby <filename>.

Ruby syntax

Classic Hello world example:

puts 'Hello World!'

Some basic Ruby code:

# Everything, including a literal, is an object, so this works: -199.abs # => 199 'ice is nice'.length # => 11 'ruby is cool.'.index('u') # => 1 "Nice Day Isn't It?".downcase.split('').uniq.sort.join # => " '?acdeinsty"

Input: print 'Please type name >' name = gets.chomp puts "Hello #{ name}." Conversions:

puts 'Give me a number'

number = gets.chomp

puts number.to_i

output_number = number.to_i + 1

puts output_number.to_s + ' is a bigger number.'

Strings

There are a variety of ways to define strings in Ruby.

The following assignments are equivalent:

a = "\nThis is a double-quoted string\n" a = %Q{ \nThis is a double-quoted string\n} a = %{ \nThis is a double-quoted string\n} a = %/\nThis is a double-quoted string\n/ a = <<-BLOCK

This is a double-quoted string

BLOCK

Strings support variable interpolation:

var = 3.14159

"pi is #{ var}" => "pi is 3.14159"

The following assignments are equivalent and produce raw strings:

a = 'This is a single-quoted string'

a = %q{ This is a single-quoted string}

Collections

Constructing and using an array:

a = [3, 'hello', 14.5, 1, 2, [6, 15]]

a[2] # => 14.5

a.[](2) # => 14.5

a.reverse # => [[6, 15], 2, 1, 14.5, 'hello', 3]

a.flatten.uniq # => [3, 'hello', 14.5, 1, 2, 6, 15]

Constructing and using an associative array (in Ruby, called a hash):

hash = Hash.new # equivalent to hash = { }

hash = { water: 'wet', fire: 'hot' } # makes the previous line redundant as we are now # assigning hash to a new, separate hash object puts hash[:fire] # prints "hot"

hash.each_pair do |key, value| # or: hash.each do |key, value|

puts "#{ key} is #{ value}" end # returns { :water=>"wet", :fire=>"hot"} and prints: # water is wet # fire is hot

hash.delete :water # deletes the pair :water => 'wet' and returns "wet" hash.delete_if { |key,value| value == 'hot'} # deletes the pair :fire => 'hot' and returns { }

Control structures

If statement:

# Generate a random number and print whether it's even or odd. if rand(100).even? puts "It's even" else puts "It's odd" end

Blocks and iterators

The two syntaxes for creating a code block: