Ruby Language Flashcards
Ruby is…
A dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write.
-A scripting language, meaning interpreted and can be used to replace batch files and shell scripts, orchestrating the behavior of other programs and the underlying operating system. Perl, TCL, and Python have all been called scripting languages.
Ruby is a genuine object-oriented language. Everything you manipulate is an object, and the results of those manipulations are themselves objects. However, many languages make the same claim, and they often have a different interpretation of what object-oriented means and a different terminology for the concepts they employ.
Ruby string manipulation
- str.slice(fixnum) or str.slice(fixnum, fixnum). Can use square brackets instead. Deletes the specified portion from str, and returns the portion deleted.
- str.split(delimiter): Divides str into substrings based on a delimiter, returning an array of these substrings
- str.strip: removes trailing whitespace
- str.length: return length of str
- str.include? other_str
- str.delete(other_str)
- str.chop: removes last char
- str.chomp
- str.chomp: Removes the record separator ($/), usually \n, from the end of a string. If no record separator exists, does nothing.
- str.inspect: returns printable version of str, with printable chars escaped
- str.reverse: returns new string with chars of str in reverse order
- str.swapcase
Ruby - create a new object (an array for this example)
names = Array.new
Also, can do names = Array.new(4, “mac”) for [“mac”, “mac”, “mac”, “mac”]
Ruby array manipulation
- array & other_array - returns new array common to both, with NO DUPLICATES
- array | other_array - returns new array containing elements either in array or other_array, with NO DUPLICATES
- array.clear: removes all elements from array
- array.map! { |item| block }: Invokes block once for each element of self, replacing the element with the value returned by block.
- array.delete(obj) [or] array.delete(obj) { block }: Deletes items from self that are equal to obj. If the item is not found, returns nil. If the optional code block is given, returns the result of block if the item is not found.
- array.delete_at(index)
- array.each { |item| block }: Calls block once for each element in self, passing that element as a parameter.
- array.hash: Computes a hash-code for array. Two arrays with the same content will have the same hash code.
- array.shift: Returns the first element of self and removes it (shifting all other elements down by one). Returns nil if the array is empty.
Ruby - Create a new hash
months = Hash.new
or
H = Hash[“a” => 100, “b” => 200]
hash.delete_if { |key,value| block }
- hash.delete_if { |key,value| block }: Deletes a key-value pair from hash for every pair the block evaluates to true.
- hash.invert: inverts keys and values
- hash.keys: array of the keys
- hash.to_a: Creates a two-dimensional array from hash. Each key/value pair is converted to an array, and all these arrays are stored in a containing array.
- hash.to_s: Converts hash to an array, then converts that array to a string
The features of an object-oriented programming language include:
Data Encapsulation
Data Abstraction
Polymorphism
Inheritance
Ruby is a perfect Object Oriented Programming Language
Local variables
Local variables are the variables that are defined in a method. Local variables are not available outside the method. You will see more details about method in subsequent chapter. Local variables begin with a lowercase letter or _
Instance variables
Instance variables are available across methods for any particular instance or object. That means that instance variables change from object to object. Instance variables are preceded by the at sign (@) followed by the variable name
Class variables
Class variables are available across different objects. A class variable belongs to the class and is a characteristic of a class. They are preceded by the sign @@ and are followed by the variable name
Global variables
Class variables are not available across classes. If you want to have a single variable, which is available across classes, you need to define a global variable. The global variables are always preceded by the dollar sign ($)
Initialize method
The initialize method is a standard Ruby class method and works almost same way as constructor works in other object oriented programming languages. The initialize method is useful when you want to initialize some class variables at the time of object creation. This method may take a list of parameters and like any other ruby method it would be preceded by def keyword
class Box def initialize(w,h) @width, @height = w, h end
# instance method
def getArea
@width * @height
end
# accessor methods
def printWidth
@width
end
def printHeight
@height
end
end
3 levels of protection at instance method level
Public Methods − Public methods can be called by anyone. Methods are public by default except for initialize, which is always private.
Private Methods − Private methods cannot be accessed, or even viewed from outside the class. Only the class methods can access private members. Protected Methods − A protected method can be invoked only by objects of the defining class and its subclasses. Access is kept within the family.
Ruby ranges
(1. .5) => 1, 2, 3, 4, 5 (inclusive!)
(1. ..5) => 1, 2, 3, 4 (not inclusive!)
Ranges are objects!
Ruby iterator
Iterators are nothing but methods supported by collections. Objects that store a group of data members are called collections. In Ruby, arrays and hashes can be termed collections.
Iterators return all the elements of a collection, one after the other. We will be discussing two iterators here, each and collect. Let’s look at these in detail.
Ruby - ‘each’ iterator
The each iterator returns all the elements of an array or a hash.
collection.each do |variable|
code
end
Executes code for each element in collection. Here, collection could be an array or a ruby hash.
Ruby - ‘collect’ iterator
The collect iterator returns all the elements of a collection.
collection = collection.collect
The collect method need not always be associated with a block. The collect method returns the entire collection, regardless of whether it is an array or a hash.
What are sockets?
Sockets are the endpoints of a bidirectional communications channel. Sockets may communicate within a process, between processes on the same machine, or between processes on different continents.
Sockets may be implemented over a number of different channel types: Unix domain sockets, TCP, UDP, and so on. The socket provides specific classes for handling the common transports as well as a generic interface for handling the rest.
Yield keyword
the mechanism of yielding to blocks in Ruby provides the programmer with a great flexibility. A block is simply a chunk of code, and yield allows you to “inject” that code at some place into a function. So if you want your function to work in a slightly different way, you don’t have to write a new function, instead you can reuse the one you already have, but give it a different block.
Law of Demeter
The LawOfDemeter specifies a style guideline: “Only talk to your immediate friends.” E.g. one never calls a method on an object you got from another call nor on a global object. This helps a lot later when you ReFactor the code.
Ruby modules
Modules are a way of grouping together methods, classes, and constants. Modules give you two major benefits.
Modules provide a namespace and prevent name clashes.
Modules implement the mixin facility.
Modules define a namespace, a sandbox in which your methods and constants can play without having to worry about being stepped on by other methods and constants.
The require statement is similar to the include statement of C and C++ and the import statement of Java. If a third program wants to use any defined module, it can simply load the module files using the Ruby require statement
Like class methods, whenever you define a method in a module, you specify the module name followed by a dot and then the method name.
$LOAD_PATH «_space;’.’ to make Ruby aware that included files must be searched in the current directory. If you do not want to use $LOAD_PATH then you can use require_relative to include files from a relative directory.
‘include’ keyword can be used to embed a module in a class
Mixins
Before going through this section, we assume you have the knowledge of Object Oriented Concepts.
When a class can inherit features from more than one parent class, the class is supposed to show multiple inheritance.
Ruby does not support multiple inheritance directly but Ruby Modules have another wonderful use. At a stroke, they pretty much eliminate the need for multiple inheritance, providing a facility called a mixin.
Mixins give you a wonderfully controlled way of adding functionality to classes. However, their true power comes out when the code in the mixin starts to interact with code in the class that uses it.
Singleton pattern
Ruby has a Singleton module to implement the Singleton pattern. Writing “include Singleton” in a class ensures only one instance of that class can be created
Ruby DSL
A domain-specific language (DSL) is a computer language specialized to a particular application domain. This is in contrast to a general-purpose language (GPL), which is broadly applicable across domains, and lacks specialized features for a particular domain.
A Domain-Specific Language, or DSL, is “a programming language of limited expressiveness focused on a particular domain”. It makes tasks in its domain easier by removing extraneous code for a particular task and allowing you to focus on the specific task at hand. It also helps other people read the code, because the purpose of the code is so clear. Known as Metaprogramming.
Part of definition of a DSL is it is not possible to write arbitrary algorithms with them.
Examples include routing, Rspec, rake tasks, capistrano, db migrations,