Ruby Language Flashcards

1
Q

Ruby is…

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Ruby string manipulation

A
  • 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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Ruby - create a new object (an array for this example)

A

names = Array.new

Also, can do names = Array.new(4, “mac”) for [“mac”, “mac”, “mac”, “mac”]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Ruby array manipulation

A
  • 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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Ruby - Create a new hash

A

months = Hash.new
or
H = Hash[“a” => 100, “b” => 200]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

hash.delete_if { |key,value| block }

A
  • 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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

The features of an object-oriented programming language include:

A

Data Encapsulation
Data Abstraction
Polymorphism
Inheritance

Ruby is a perfect Object Oriented Programming Language

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Local variables

A

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 _

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Instance variables

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Class variables

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Global variables

A

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 ($)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Initialize method

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

3 levels of protection at instance method level

A

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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Ruby ranges

A

(1. .5) => 1, 2, 3, 4, 5 (inclusive!)
(1. ..5) => 1, 2, 3, 4 (not inclusive!)

Ranges are objects!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Ruby iterator

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Ruby - ‘each’ iterator

A

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.

17
Q

Ruby - ‘collect’ iterator

A

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.

18
Q

What are sockets?

A

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.

19
Q

Yield keyword

A

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.

20
Q

Law of Demeter

A

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.

21
Q

Ruby modules

A

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 &laquo_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

22
Q

Mixins

A

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.

23
Q

Singleton pattern

A

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

24
Q

Ruby DSL

A

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,

25
Q

yield keyword

A

On the recipients side, there are a couple ways to receive the block that was passed. The first way is via the yield keyword in Ruby. yield will call the block of code that was passed to the method. You can even pass variables to the block of code.

26
Q

named-block

A

There is an alternate way of receiving a block of code that is called a named-block (as opposed to yield). This essentially allows you to save the block of code to a variable, which gives you the flexibility to pass the block on to another method. If you wish to execute the code inside of the block, you can do so via the call method on it.

27
Q

How to create a DSL

A

Use the DSL module, which has a method ‘define’

module DSL 
  def self.define(name, &block)
    p name
    definition = Definition.new
    if block_given?
      definition.instance_eval(&block)
    end
  end
end
28
Q

and vs &&, or vs ||

A

Although these two statements might appear to be equivalent, they are not, due to the order of operations. Specifically, the and and or operators have lower precedence than the = operator, whereas the && and || operators have higher precedence than the = operator, based on order of operations.

To help clarify this, here’s the same code, but employing parentheses to clarify the default order of operations:

(val1 = true) and false # results in val1 being equal to true
val2 = (true && false) # results in val2 being equal to false
This is, incidentally, a great example of why using parentheses to clearly specify your intent is generally a good practice, in any language. But whether or not you use parentheses, it’s important to be aware of these order of operations rules and to thereby ensure that you are properly determining when to employ and / or vs. && / ||.

29
Q

What evaluates to false in Ruby

A

In Ruby, the only values that evaluate to false are false and nil. Everything else – even zero (0) and an empty array ([]) – evaluates to true.