By - scmGalaxy.com

About Me !

RUBY

Ruby is a dynamic, reflective, general-purpose object-oriented programming language.The original author is a Japanese programmer Yukihiro Matsumoto. Ruby first appeared in 1995.

GOAL

The goal of this tutorial is to get you started with the Ruby programming language, so that it helps to understand Chef.The tutorial covers the core of the Ruby language, including variables, expressions, collections, control structures and other core features. It is not a complete coverage of the language.

ABOUT RUBY

Ruby supports various programming paradigms. This includes object orientation, reflection, imperative and reflective programming.Ruby language was influenced primarily by Perl, Smalltalk, Eiffel, and Lisp.Unlike languages like Java, C# or C, Ruby has no official specification. There are other implementations of the Ruby language like JRuby, IronRuby, or MacRuby.

POPULARITY

There are hundreds of programming languages in use today. Ruby belongs to the most popular ones.The langpop.com and tiobe sites put Ruby around the 10th place.Ruby on Rails, a very popular web application framework is the first killer application created in Ruby.

INTERACTIVE INTERPRETER

We can run Ruby statements in a script or in an interactive interpreter.In this tutorial, we will use the interactive Ruby session to demonstrate some smaller code fragments. Larger code examples are to be put in Ruby scripts.


$ irb
irb(main):001:0> puts RUBY_VERSION
1.8.7
=> nil

This is an example of the Ruby interactive session.

RUBY SCRIPTS

This is the simplest possible Ruby program, hello.rb. As you'd expect, it prints "Hello World" on the screen.

#!/usr/bin/ruby
# first.rb 

puts "This is Ruby"

Be sure to set it executable.

WHILE LOOPS

Ruby includes a while loop that will execute a block of code as long as its condition is true. When the condition becomes false, the code after the end of the loop will be executed.

Syntax :
while condition_is_true
# do something
end

Example :
i = 1
while i < 5
  puts "#{i} is less than 5!"
  i += 1
end
puts "Done!"

1 is less than 5!
2 is less than 5!
3 is less than 5!
4 is less than 5!
Done!

UNTIL LOOPS

Ruby includes an until loop that will execute a block of code as long as its condition is false.When the condition becomes true, the code after the end of the loop will be executed.

Syntax :
until condition_is_false
  # do something
end
Example :
counter = 3
until counter <= 0 
  puts counter
  counter -= 1
end
puts "Blast off!"
			
Output :
3
2
1
Blast off!

FOR LOOPS

The for loop is used to iterate an object.The Ruby .each method is preferred over the for loop because the for loop does not create a new scope for the object whereas the .each method does. The for loop is rare in Ruby.

Syntax :
for iterator in iterable_object
  # do something
end

Example :
for number in (0..5)
  puts number
end
			
Output :
0
1
2
3
4
5

Example :
my_array = ["Matz", "chunky", "bacon"]
for item in my_array
  puts item
end

output :
Matz
chunky
bacon

OBJECTS & METHODS IN RUBY

There are two kinds of objects: built-in objects and custom objects.Built-in objects are predefined objects that all programmers can use.They are available with the core of the Ruby language or from various libraries. Custom objects are created by application programmers for their application domains.

Ruby is a pure object-oriented language and things are a bit different. The "Ruby language" is a indeed a string, which is a common data type. But it is also an object. And as with all objects, we can call its methods. This is a bit different from other languages. The puts is a method. A Ruby method is used to create parameterized, reusable code. Ruby methods can be created using the syntax:

Syntax :
def method_name(arguments)
  # Code to be executed
end

Example :
def sum(x,y)
  x + y
end

sum(13, 379)
=> 392

A method is a function defined in an object. Methods do not exist on their own. In fact, the puts method is a part of the Kernel module.

Example :
#!/usr/bin/ruby
			
Kernel.puts "Ruby language"
Kernel.puts "Ruby language".size

Output :

$ ./simple2.rb
			
Ruby language
13

VARIABLES AND CONSTANTS

#!/usr/bin/ruby

city = "New York"
name = "Paul"; age = 35
nationality = "American"

puts city
puts name
puts age
puts nationality

city = "London"

puts city

$ ./variables.rb 
New York
Paul
35
American
London
Output of the example.

Constants store one value over the time. Unlike in other languages, this rule is however not enforced in Ruby.

#!/usr/bin/ruby

 WIDTH = 100
 HEIGHT = 150

 var = 40
 puts var

 var = 50
 puts var

 puts WIDTH
 WIDTH = 110
 puts WIDTH

In this example, we declare two constants and one variable.

	WIDTH = 100
	HEIGHT = 150
Constants in Ruby begin with capital letter. It is a common practice to write all characters of a constant in uppercase letters.
 var = 40
 puts var

 var = 50

We declare and initialize a variable. Later, we assign a new value to the variable. It is legal.

 WIDTH = 110

We assign a new value to a constant. Constants should not be modified, once they are created. Otherwise it has no meaning to create a constant. The Ruby interpreter will issue a warning.

$ ./constants.rb 
40
50
100
./constants.rb:13: warning: already initialized constant WIDTH
110

Output of the script.

VARIABLE INTERPOLATION

Variable interpolation is replacing variables with their values inside string literals. Other names for variable interpolation are variable substitution and variable expansion.

#!/usr/bin/ruby

age = 34
name = "William"

puts "#{name} is #{age} years old"

In Ruby, strings are immutable. We cannot modify an existing string. Variable interpolation happens during string creation.

 puts "#{name} is #{age} years old"

The string message has double quotes as its boundaries. When we put a variable name between the #{ and } characters, the variable is interpolated: that is, replaced with its value.

 $ ./interpolation.rb 
 William is 34 years old

ARRAYS

An array is a Ruby data type that holds an ordered collection of values,which can be any type of object including other arrays.

CREATING ARRAYS

Ruby arrays can be created with either literal notation or the Array.new constructor.

Syntax
# Array.new constructor
variable = Array.new([repeat], [item])
			
Example
empty_arr = Array.new
=> []
matzes = Array.new(3, "Matz!")
=> ["Matz!", "Matz!", "Matz!"]

ARRAY.EACH

You can iterate over the elements in an array using Array.each, which takes a block.

Syntax :
array.each do |arg|
  # Do something to each element, referenced as arg
end
			
#or

array.each { |arg|
  # Do something to each element, referenced as arg
}
Example :
["Ryan", "Zach"].each do |person|
  "#{person} is such a great guy!"
end
			
Output :
Ryan is such a great guy!
Zach is such a great guy!

ARRAY.UNIQ

You can remove duplicates from an array using Array.uniq.

Example :
[1,1,1,2,3,4,3,3].uniq
		
=> [1,2,3,4]

SWITCH STATEMENT

Acts like a big if / else if / else chain. Checks a value against a list of cases, and executes the first case that is true.If it does not find a match, it attempts the default case designated by an else statement.If there is not a default case, then it exits the statement.Unlike languages like JavaScript, Ruby switch statements have no fall through and automatically break.Instead, cases can be comma delimited.

Syntax:
case value

when expression1
  #do something
when expression2
  #do something
...
when expressionN
  #do something
else
  #do default case
end
Example :

a = ["4"]
case a
when 1..4, 5
  puts "It's between 1 and 5"
when 6	
  puts "It's 6"
when String
  puts "You passed a string"
else
  puts "You gave me #{a} -- I have no idea what to do with that."
end
		
=> You gave me 4 -- I have no idea what to do with that.

BLOCKS

A block is a chunk of code that lives inside a control statement, loop, method definition, or method call. It returns the value of its last line. In Ruby, blocks can be created two ways: with braces or with a do/end statement.

Syntax :
						
# Blocks that span only one line usually use the braces form
objs.method { |obj| do_something }
Example :

[1,2,3,4].each { |number| puts number }

1
2
3
4
Syntax :

# Blocks that span multiple lines usually use the do/end form
objs.method do |obj|
  # do first line
  # do second line
  # ...
  # do nth line
end
Example :

[1,2,3,4].each do |number|
  puts "You know what number I love?"
  puts "I love #{number}!"
end

You know what number I love?
I love 1!
You know what number I love?
I love 2!
You know what number I love?
I love 3!
You know what number I love?
I love 4!

HASHES

Hashes are collections of key-value pairs. Like arrays, they have values associated with indices, but in the case of hashes, the indices are called "keys." Keys can be anything that's hashable, such as integers, strings, or symbols, but they must be unique for the hash they belong. The values to which keys refer can be any Ruby object.

CREATING STANDARD HASHES

There are several ways to create hashes in Ruby. The common most two are the new constructor method and its literal notation. It is also considered a best practice to use symbols as keys. The following are valid in all versions of Ruby.

Syntax :

# Hash.new constructor
my_hash = Hash.new([default_value])
Example :

empty_hash = Hash.new
=> {}

my_hash = Hash.new("The Default")
my_hash["random_key"]
=> "The Default"
Syntax :

# Hash literal notation
my_hash = {
"key1" => value1,
  :key2  => value2,
  3 => value 3
}
Example :

my_hash = {
  :a => "Artur",
  :l => "Linda",
  :r => "Ryan",
  :z => "Zach"
}
=> {:a => "Artur", :l => "Linda", :r => "Ryan", :z => "Zach"}

CREATING SHORTHAND HASHES

As of Ruby 1.9, there is now a shorthand method for writing hashes that's a lot easier to write. Rather than specifying a symbol then using the hash rockets to define key value pairs, you can now just put the key followed by a colon then the value. The keys get translated into symbols.

Syntax :

my_hash = {
  key1: value1,
  key2: value2
}
Example :

my_hash = {
  name: "Artur",
  age:  21
}
=> { :name => "Artur", :age => 21 }

Questions ??

Thanks !!