SlideShare uma empresa Scribd logo
1 de 7
Baixar para ler offline
RUBY OPERATORS
http://www.tutorialspoint.com/ruby/ruby_operators.htm                                            Copyright © tutorialspoint.com



Ruby supports a rich set of operators, as you'd expect from a modern language. Most operators are actually method
calls. For example, a + b is interpreted as a.+(b), where the + method in the object referred to by variable a is called
with b as its argument.

For each operator (+ - * / % ** & | ^ << >> && ||), there is a corresponding form of abbreviated assignment operator
(+= -= etc.)

Ruby Arithmetic Operators:

Assume variable a holds 10 and variable b holds 20 then:



 Operator       Description                                            Example

 +              Addition - Adds values on either side of the           a + b will give 30
                operator

 -              Subtraction - Subtracts right hand operand from        a - b will give -10
                left hand operand

 *              Multiplication - Multiplies values on either side of   a * b will give 200
                the operator

 /              Division - Divides left hand operand by right hand     b / a will give 2
                operand

 %              Modulus - Divides left hand operand by right hand      b % a will give 0
                operand and returns remainder

 **             Exponent - Performs exponential (power)                a**b will give 10 to the power 20
                calculation on operators



Ruby Comparison Operators:

Assume variable a holds 10 and variable b holds 20 then:



 Operator       Description                                            Example

 ==             Checks if the value of two operands are equal or       (a == b) is not true.
                not, if yes then condition becomes true.

 !=             Checks if the value of two operands are equal or       (a != b) is true.
                not, if values are not equal then condition becomes
                true.

 >              Checks if the value of left operand is greater than    (a > b) is not true.
                the value of right operand, if yes then condition
                becomes true.
<            Checks if the value of left operand is less than the    (a < b) is true.
              value of right operand, if yes then condition
              becomes true.

 >=           Checks if the value of left operand is greater than     (a >= b) is not true.
              or equal to the value of right operand, if yes then
              condition becomes true.

 <=           Checks if the value of left operand is less than or     (a <= b) is true.
              equal to the value of right operand, if yes then
              condition becomes true.

 <=>          Combined comparison operator. Returns 0 if first        (a <=> b) returns -1.
              operand equals second, 1 if first operand is greater
              than the second and -1 if first operand is less than
              the second.

 ===          Used to test equality within a when clause of a         (1...10) === 5 returns true.
              case statement.

 .eql?        True if the receiver and argument have both the         1 == 1.0 returns true, but 1.eql?(1.0) is false.
              same type and equal values.

 equal?       True if the receiver and argument have the same         1 == 1.0 returns true, but 1.eql?(1.0) is false.
              object id.



Ruby Assignment Operators:

Assume variable a holds 10 and variable b holds 20 then:



 Operator     Description                                       Example

 =            Simple assignment operator, Assigns values        c = a + b will assigne value of a + b into c
              from right side operands to left side operand

 +=           Add AND assignment operator, It adds right        c += a is equivalent to c = c + a
              operand to the left operand and assign the
              result to left operand

 -=           Subtract AND assignment operator, It              c -= a is equivalent to c = c - a
              subtracts right operand from the left operand
              and assign the result to left operand

 *=           Multiply AND assignment operator, It              c *= a is equivalent to c = c * a
              multiplies right operand with the left
              operand and assign the result to left operand

 /=           Divide AND assignment operator, It divides        c /= a is equivalent to c = c / a
              left operand with the right operand and
              assign the result to left operand

 %=           Modulus AND assignment operator, It takes         c %= a is equivalent to c = c % a
              modulus using two operands and assign the
              result to left operand
**=            Exponent AND assignment operator,                 c **= a is equivalent to c = c ** a
                Performs exponential (power) calculation on
                operators and assign value to the left
                operand



Ruby Parallel Assignment:

Ruby also supports the parallel assignment of variables. This enables multiple variables to be initialized with a single
line of Ruby code. For example:

 a = 10
 b = 20
 c = 30


may be more quickly declared using parallel assignment:

 a, b, c = 10, 20, 30


Parallel assignment is also useful for swapping the values held in two variables:

 a, b = b, c


Ruby Bitwise Operators:

Bitwise operator works on bits and perform bit by bit operation.

Assume if a = 60; and b = 13; Now in binary format they will be as follows:

a = 0011 1100

b = 0000 1101

-----------------

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

There are following Bitwise operators supported by Ruby language



 Operator       Description                                             Example

 &              Binary AND Operator copies a bit to the result if       (a & b) will give 12 which is 0000 1100
                it exists in both operands.

 |              Binary OR Operator copies a bit if it exists in         (a | b) will give 61 which is 0011 1101
                eather operand.

 ^              Binary XOR Operator copies the bit if it is set in      (a ^ b) will give 49 which is 0011 0001
                one operand but not both.
~            Binary Ones Complement Operator is unary and           (~a ) will give -60 which is 1100 0011
              has the efect of 'flipping' bits.

 <<           Binary Left Shift Operator. The left operands          a << 2 will give 240 which is 1111 0000
              value is moved left by the number of bits specified
              by the right operand.

 >>           Binary Right Shift Operator. The left operands         a >> 2 will give 15 which is 0000 1111
              value is moved right by the number of bits
              specified by the right operand.



Ruby Logical Operators:

There are following logical operators supported by Ruby language

Assume variable a holds 10 and variable b holds 20 then:



 Operator     Description                                            Example

 and          Called Logical AND operator. If both the               (a and b) is true.
              operands are true then then condition becomes
              true.

 or           Called Logical OR Operator. If any of the two          (a or b) is true.
              operands are non zero then then condition becomes
              true.

 &&           Called Logical AND operator. If both the               (a && b) is true.
              operands are non zero then then condition becomes
              true.

 ||           Called Logical OR Operator. If any of the two          (a || b) is true.
              operands are non zero then then condition becomes
              true.

 !            Called Logical NOT Operator. Use to reverses the       !(a && b) is false.
              logical state of its operand. If a condition is true
              then Logical NOT operator will make false.

 not          Called Logical NOT Operator. Use to reverses the       not(a && b) is false.
              logical state of its operand. If a condition is true
              then Logical NOT operator will make false.



Ruby Ternary operator:

There is one more oprator called Ternary Operator. This first evaluates an expression for a true or false value and then
execute one of the two given statements depending upon the result of the evaluation. The conditioanl operator has this
syntax:


 Operator     Description                                      Example

 ?:           Conditional Expression                           If Condition is true ? Then value X : Otherwise value Y
Ruby Range operators:

Sequence ranges in Ruby are used to create a range of successive values - consisting of a start value, an end value and a
range of values in between.

In Ruby, these sequences are created using the ".." and "..." range operators. The two-dot form creates an inclusive
range, while the three-dot form creates a range that excludes the specified high value.


 Operator      Description                                     Example

 ..            Creates a range from start point to end point   1..10 Creates a range from 1 to 10 inclusive
               inclusive

 ...           Creates a range from start point to end point   1...10 Creates a range from 1 to 9
               exclusive



Ruby defined? operators:

defined? is a special operator that takes the form of a method call to determine whether or not the passed expression is
defined. It returns a description string of the expression, or nil if the expression isn't defined.

There are various usage of defined? operator:

Usage 1

 defined? variable # True if variable is initialized


For Example:

 foo = 42
 defined? foo        # => "local-variable"
 defined? $_         # => "global-variable"
 defined? bar        # => nil (undefined)


Usage 2

 defined? method_call # True if a method is defined


For Example:

 defined? puts               # => "method"
 defined? puts(bar)          # => nil (bar is not defined here)
 defined? unpack             # => nil (not defined here)


Usage 3

 # True if a method exists that can be called with super user
 defined? super


For Example:

 defined? super          # => "super" (if it can be called)
 defined? super          # => nil (if it cannot be)
Usage 4

 defined? yield       # True if a code block has been passed


For Example:

 defined? yield         # => "yield" (if there is a block passed)
 defined? yield         # => nil (if there is no block)


Ruby dot "." and double Colon "::" Operators:

You call a module method by preceding its name with the module's name and aperiod, and you reference a constant
using the module name and two colons.

The :: is a unary operator that allows: constants, instance methods and class methods defined within a class or module,
to be accessed from anywhere outside the class or module.

Remember: in Ruby, classes and methods may be considered constants too.

You need just to prefix the :: Const_name with an expression that returns the appropriate class or module object.

If no prefix expression is used, the main Object class is used by default.

Here are two examples:

 MR_COUNT = 0             # constant defined on main Object class
 module Foo
   MR_COUNT = 0
   ::MR_COUNT = 1         # set global count to 1
   MR_COUNT = 2           # set local count to 2
 end
 puts MR_COUNT            # this is the global constant
 puts Foo::MR_COUNT       # this is the local "Foo" constant


Second Example:

 CONST = ' out there'
 class Inside_one
    CONST = proc {' in there'}
    def where_is_my_CONST
       ::CONST + ' inside one'
    end
 end
 class Inside_two
    CONST = ' inside two'
    def where_is_my_CONST
       CONST
    end
 end
 puts Inside_one.new.where_is_my_CONST
 puts Inside_two.new.where_is_my_CONST
 puts Object::CONST + Inside_two::CONST
 puts Inside_two::CONST + CONST
 puts Inside_one::CONST
 puts Inside_one::CONST.call + Inside_two::CONST


Ruby Operators Precedence

The following table lists all operators from highest precedence to lowest.
Method                 Operator                                                Description

 Yes       ::                                    Constant resolution operator

 Yes       [ ] [ ]=                              Element reference, element set

 Yes       **                                    Exponentiation (raise to the power)

 Yes       !~+-                                  Not, complement, unary plus and minus (method names for the
                                                 last two are +@ and -@)

 Yes       */%                                   Multiply, divide, and modulo

 Yes       +-                                    Addition and subtraction

 Yes       >> <<                                 Right and left bitwise shift

 Yes       &                                     Bitwise 'AND'

 Yes       ^|                                    Bitwise exclusive `OR' and regular `OR'

 Yes       <= < > >=                             Comparison operators

 Yes       <=> == === != =~ !~                   Equality and pattern match operators (!= and !~ may not be
                                                 defined as methods)

           &&                                    Logical 'AND'

           ||                                    Logical 'OR'

           .. ...                                Range (inclusive and exclusive)

           ?:                                    Ternary if-then-else

           = %= { /= -= += |= &= >>= <<= *=      Assignment
           &&= ||= **=

           defined?                              Check if specified symbol defined

           not                                   Logical negation

           or and                                Logical composition


NOTE: Operators with a Yes in the method column are actually methods, and as such may be overridden.

Mais conteúdo relacionado

Mais procurados

Operator & Expression in c++
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++bajiajugal
 
Operators and Expressions in Java
Operators and Expressions in JavaOperators and Expressions in Java
Operators and Expressions in JavaAbhilash Nair
 
Operators and Expressions in C++
Operators and Expressions in C++Operators and Expressions in C++
Operators and Expressions in C++Praveen M Jigajinni
 
Operators and expressions
Operators and expressionsOperators and expressions
Operators and expressionsvishaljot_kaur
 
Operation and expression in c++
Operation and expression in c++Operation and expression in c++
Operation and expression in c++Online
 
Chapter 5 - Operators in C++
Chapter 5 - Operators in C++Chapter 5 - Operators in C++
Chapter 5 - Operators in C++Deepak Singh
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++Neeru Mittal
 
Programming Fundamentals lecture 7
Programming Fundamentals lecture 7Programming Fundamentals lecture 7
Programming Fundamentals lecture 7REHAN IJAZ
 
java operators
 java operators java operators
java operatorsJadavsejal
 
operators and expressions in c++
 operators and expressions in c++ operators and expressions in c++
operators and expressions in c++sanya6900
 
Expressions in c++
 Expressions in c++ Expressions in c++
Expressions in c++zeeshan turi
 
Mesics lecture 4 c operators and experssions
Mesics lecture  4   c operators and experssionsMesics lecture  4   c operators and experssions
Mesics lecture 4 c operators and experssionseShikshak
 

Mais procurados (20)

Operator & Expression in c++
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++
 
Operators and Expressions in Java
Operators and Expressions in JavaOperators and Expressions in Java
Operators and Expressions in Java
 
Operators and Expressions in C++
Operators and Expressions in C++Operators and Expressions in C++
Operators and Expressions in C++
 
Operators and expressions
Operators and expressionsOperators and expressions
Operators and expressions
 
Operation and expression in c++
Operation and expression in c++Operation and expression in c++
Operation and expression in c++
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Operators
OperatorsOperators
Operators
 
Operators in c++
Operators in c++Operators in c++
Operators in c++
 
Chapter 5 - Operators in C++
Chapter 5 - Operators in C++Chapter 5 - Operators in C++
Chapter 5 - Operators in C++
 
C – operators and expressions
C – operators and expressionsC – operators and expressions
C – operators and expressions
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
 
C++ chapter 2
C++ chapter 2C++ chapter 2
C++ chapter 2
 
Programming Fundamentals lecture 7
Programming Fundamentals lecture 7Programming Fundamentals lecture 7
Programming Fundamentals lecture 7
 
Operators in C & C++ Language
Operators in C & C++ LanguageOperators in C & C++ Language
Operators in C & C++ Language
 
Java 2
Java 2Java 2
Java 2
 
java operators
 java operators java operators
java operators
 
operators and expressions in c++
 operators and expressions in c++ operators and expressions in c++
operators and expressions in c++
 
Operators
OperatorsOperators
Operators
 
Expressions in c++
 Expressions in c++ Expressions in c++
Expressions in c++
 
Mesics lecture 4 c operators and experssions
Mesics lecture  4   c operators and experssionsMesics lecture  4   c operators and experssions
Mesics lecture 4 c operators and experssions
 

Destaque (6)

19 ruby iterators
19 ruby iterators19 ruby iterators
19 ruby iterators
 
17 ruby date time
17 ruby date time17 ruby date time
17 ruby date time
 
16 ruby hashes
16 ruby hashes16 ruby hashes
16 ruby hashes
 
18 ruby ranges
18 ruby ranges18 ruby ranges
18 ruby ranges
 
20 ruby input output
20 ruby input output20 ruby input output
20 ruby input output
 
15 ruby arrays
15 ruby arrays15 ruby arrays
15 ruby arrays
 

Semelhante a 07 ruby operators

Semelhante a 07 ruby operators (20)

itft-Operators in java
itft-Operators in javaitft-Operators in java
itft-Operators in java
 
Session03 operators
Session03 operatorsSession03 operators
Session03 operators
 
Java basic operators
Java basic operatorsJava basic operators
Java basic operators
 
Operator 04 (js)
Operator 04 (js)Operator 04 (js)
Operator 04 (js)
 
Opeartor &amp; expression
Opeartor &amp; expressionOpeartor &amp; expression
Opeartor &amp; expression
 
Operators in Python
Operators in PythonOperators in Python
Operators in Python
 
Python operators part2
Python operators part2Python operators part2
Python operators part2
 
python operators.ppt
python operators.pptpython operators.ppt
python operators.ppt
 
Bit shift operators
Bit shift operatorsBit shift operators
Bit shift operators
 
C programming operators
C programming operatorsC programming operators
C programming operators
 
Py-Slides-2.ppt
Py-Slides-2.pptPy-Slides-2.ppt
Py-Slides-2.ppt
 
Py-Slides-2 (1).ppt
Py-Slides-2 (1).pptPy-Slides-2 (1).ppt
Py-Slides-2 (1).ppt
 
Py-Slides-2.ppt
Py-Slides-2.pptPy-Slides-2.ppt
Py-Slides-2.ppt
 
Operators used in vb.net
Operators used in vb.netOperators used in vb.net
Operators used in vb.net
 
Operators and it's type
Operators and it's type Operators and it's type
Operators and it's type
 
Python tutorials for beginners | IQ Online Training
Python tutorials for beginners | IQ Online TrainingPython tutorials for beginners | IQ Online Training
Python tutorials for beginners | IQ Online Training
 
Programming C Part 02
Programming C Part 02Programming C Part 02
Programming C Part 02
 
Java unit1 b- Java Operators to Methods
Java  unit1 b- Java Operators to MethodsJava  unit1 b- Java Operators to Methods
Java unit1 b- Java Operators to Methods
 
Python : basic operators
Python : basic operatorsPython : basic operators
Python : basic operators
 
C# operators
C# operatorsC# operators
C# operators
 

Mais de Walker Maidana (16)

14 ruby strings
14 ruby strings14 ruby strings
14 ruby strings
 
13 ruby modules
13 ruby modules13 ruby modules
13 ruby modules
 
12 ruby blocks
12 ruby blocks12 ruby blocks
12 ruby blocks
 
11 ruby methods
11 ruby methods11 ruby methods
11 ruby methods
 
10 ruby loops
10 ruby loops10 ruby loops
10 ruby loops
 
09 ruby if else
09 ruby if else09 ruby if else
09 ruby if else
 
08 ruby comments
08 ruby comments08 ruby comments
08 ruby comments
 
06 ruby variables
06 ruby variables06 ruby variables
06 ruby variables
 
05 ruby classes
05 ruby classes05 ruby classes
05 ruby classes
 
04 ruby syntax
04 ruby syntax04 ruby syntax
04 ruby syntax
 
03 ruby environment
03 ruby environment03 ruby environment
03 ruby environment
 
01 index
01 index01 index
01 index
 
00 ruby tutorial
00 ruby tutorial00 ruby tutorial
00 ruby tutorial
 
02 ruby overview
02 ruby overview02 ruby overview
02 ruby overview
 
21 ruby exceptions
21 ruby exceptions21 ruby exceptions
21 ruby exceptions
 
Tutorial ruby eustaquio taq rangel
Tutorial ruby   eustaquio taq rangelTutorial ruby   eustaquio taq rangel
Tutorial ruby eustaquio taq rangel
 

07 ruby operators

  • 1. RUBY OPERATORS http://www.tutorialspoint.com/ruby/ruby_operators.htm Copyright © tutorialspoint.com Ruby supports a rich set of operators, as you'd expect from a modern language. Most operators are actually method calls. For example, a + b is interpreted as a.+(b), where the + method in the object referred to by variable a is called with b as its argument. For each operator (+ - * / % ** & | ^ << >> && ||), there is a corresponding form of abbreviated assignment operator (+= -= etc.) Ruby Arithmetic Operators: Assume variable a holds 10 and variable b holds 20 then: Operator Description Example + Addition - Adds values on either side of the a + b will give 30 operator - Subtraction - Subtracts right hand operand from a - b will give -10 left hand operand * Multiplication - Multiplies values on either side of a * b will give 200 the operator / Division - Divides left hand operand by right hand b / a will give 2 operand % Modulus - Divides left hand operand by right hand b % a will give 0 operand and returns remainder ** Exponent - Performs exponential (power) a**b will give 10 to the power 20 calculation on operators Ruby Comparison Operators: Assume variable a holds 10 and variable b holds 20 then: Operator Description Example == Checks if the value of two operands are equal or (a == b) is not true. not, if yes then condition becomes true. != Checks if the value of two operands are equal or (a != b) is true. not, if values are not equal then condition becomes true. > Checks if the value of left operand is greater than (a > b) is not true. the value of right operand, if yes then condition becomes true.
  • 2. < Checks if the value of left operand is less than the (a < b) is true. value of right operand, if yes then condition becomes true. >= Checks if the value of left operand is greater than (a >= b) is not true. or equal to the value of right operand, if yes then condition becomes true. <= Checks if the value of left operand is less than or (a <= b) is true. equal to the value of right operand, if yes then condition becomes true. <=> Combined comparison operator. Returns 0 if first (a <=> b) returns -1. operand equals second, 1 if first operand is greater than the second and -1 if first operand is less than the second. === Used to test equality within a when clause of a (1...10) === 5 returns true. case statement. .eql? True if the receiver and argument have both the 1 == 1.0 returns true, but 1.eql?(1.0) is false. same type and equal values. equal? True if the receiver and argument have the same 1 == 1.0 returns true, but 1.eql?(1.0) is false. object id. Ruby Assignment Operators: Assume variable a holds 10 and variable b holds 20 then: Operator Description Example = Simple assignment operator, Assigns values c = a + b will assigne value of a + b into c from right side operands to left side operand += Add AND assignment operator, It adds right c += a is equivalent to c = c + a operand to the left operand and assign the result to left operand -= Subtract AND assignment operator, It c -= a is equivalent to c = c - a subtracts right operand from the left operand and assign the result to left operand *= Multiply AND assignment operator, It c *= a is equivalent to c = c * a multiplies right operand with the left operand and assign the result to left operand /= Divide AND assignment operator, It divides c /= a is equivalent to c = c / a left operand with the right operand and assign the result to left operand %= Modulus AND assignment operator, It takes c %= a is equivalent to c = c % a modulus using two operands and assign the result to left operand
  • 3. **= Exponent AND assignment operator, c **= a is equivalent to c = c ** a Performs exponential (power) calculation on operators and assign value to the left operand Ruby Parallel Assignment: Ruby also supports the parallel assignment of variables. This enables multiple variables to be initialized with a single line of Ruby code. For example: a = 10 b = 20 c = 30 may be more quickly declared using parallel assignment: a, b, c = 10, 20, 30 Parallel assignment is also useful for swapping the values held in two variables: a, b = b, c Ruby Bitwise Operators: Bitwise operator works on bits and perform bit by bit operation. Assume if a = 60; and b = 13; Now in binary format they will be as follows: a = 0011 1100 b = 0000 1101 ----------------- a&b = 0000 1100 a|b = 0011 1101 a^b = 0011 0001 ~a = 1100 0011 There are following Bitwise operators supported by Ruby language Operator Description Example & Binary AND Operator copies a bit to the result if (a & b) will give 12 which is 0000 1100 it exists in both operands. | Binary OR Operator copies a bit if it exists in (a | b) will give 61 which is 0011 1101 eather operand. ^ Binary XOR Operator copies the bit if it is set in (a ^ b) will give 49 which is 0011 0001 one operand but not both.
  • 4. ~ Binary Ones Complement Operator is unary and (~a ) will give -60 which is 1100 0011 has the efect of 'flipping' bits. << Binary Left Shift Operator. The left operands a << 2 will give 240 which is 1111 0000 value is moved left by the number of bits specified by the right operand. >> Binary Right Shift Operator. The left operands a >> 2 will give 15 which is 0000 1111 value is moved right by the number of bits specified by the right operand. Ruby Logical Operators: There are following logical operators supported by Ruby language Assume variable a holds 10 and variable b holds 20 then: Operator Description Example and Called Logical AND operator. If both the (a and b) is true. operands are true then then condition becomes true. or Called Logical OR Operator. If any of the two (a or b) is true. operands are non zero then then condition becomes true. && Called Logical AND operator. If both the (a && b) is true. operands are non zero then then condition becomes true. || Called Logical OR Operator. If any of the two (a || b) is true. operands are non zero then then condition becomes true. ! Called Logical NOT Operator. Use to reverses the !(a && b) is false. logical state of its operand. If a condition is true then Logical NOT operator will make false. not Called Logical NOT Operator. Use to reverses the not(a && b) is false. logical state of its operand. If a condition is true then Logical NOT operator will make false. Ruby Ternary operator: There is one more oprator called Ternary Operator. This first evaluates an expression for a true or false value and then execute one of the two given statements depending upon the result of the evaluation. The conditioanl operator has this syntax: Operator Description Example ?: Conditional Expression If Condition is true ? Then value X : Otherwise value Y
  • 5. Ruby Range operators: Sequence ranges in Ruby are used to create a range of successive values - consisting of a start value, an end value and a range of values in between. In Ruby, these sequences are created using the ".." and "..." range operators. The two-dot form creates an inclusive range, while the three-dot form creates a range that excludes the specified high value. Operator Description Example .. Creates a range from start point to end point 1..10 Creates a range from 1 to 10 inclusive inclusive ... Creates a range from start point to end point 1...10 Creates a range from 1 to 9 exclusive Ruby defined? operators: defined? is a special operator that takes the form of a method call to determine whether or not the passed expression is defined. It returns a description string of the expression, or nil if the expression isn't defined. There are various usage of defined? operator: Usage 1 defined? variable # True if variable is initialized For Example: foo = 42 defined? foo # => "local-variable" defined? $_ # => "global-variable" defined? bar # => nil (undefined) Usage 2 defined? method_call # True if a method is defined For Example: defined? puts # => "method" defined? puts(bar) # => nil (bar is not defined here) defined? unpack # => nil (not defined here) Usage 3 # True if a method exists that can be called with super user defined? super For Example: defined? super # => "super" (if it can be called) defined? super # => nil (if it cannot be)
  • 6. Usage 4 defined? yield # True if a code block has been passed For Example: defined? yield # => "yield" (if there is a block passed) defined? yield # => nil (if there is no block) Ruby dot "." and double Colon "::" Operators: You call a module method by preceding its name with the module's name and aperiod, and you reference a constant using the module name and two colons. The :: is a unary operator that allows: constants, instance methods and class methods defined within a class or module, to be accessed from anywhere outside the class or module. Remember: in Ruby, classes and methods may be considered constants too. You need just to prefix the :: Const_name with an expression that returns the appropriate class or module object. If no prefix expression is used, the main Object class is used by default. Here are two examples: MR_COUNT = 0 # constant defined on main Object class module Foo MR_COUNT = 0 ::MR_COUNT = 1 # set global count to 1 MR_COUNT = 2 # set local count to 2 end puts MR_COUNT # this is the global constant puts Foo::MR_COUNT # this is the local "Foo" constant Second Example: CONST = ' out there' class Inside_one CONST = proc {' in there'} def where_is_my_CONST ::CONST + ' inside one' end end class Inside_two CONST = ' inside two' def where_is_my_CONST CONST end end puts Inside_one.new.where_is_my_CONST puts Inside_two.new.where_is_my_CONST puts Object::CONST + Inside_two::CONST puts Inside_two::CONST + CONST puts Inside_one::CONST puts Inside_one::CONST.call + Inside_two::CONST Ruby Operators Precedence The following table lists all operators from highest precedence to lowest.
  • 7. Method Operator Description Yes :: Constant resolution operator Yes [ ] [ ]= Element reference, element set Yes ** Exponentiation (raise to the power) Yes !~+- Not, complement, unary plus and minus (method names for the last two are +@ and -@) Yes */% Multiply, divide, and modulo Yes +- Addition and subtraction Yes >> << Right and left bitwise shift Yes & Bitwise 'AND' Yes ^| Bitwise exclusive `OR' and regular `OR' Yes <= < > >= Comparison operators Yes <=> == === != =~ !~ Equality and pattern match operators (!= and !~ may not be defined as methods) && Logical 'AND' || Logical 'OR' .. ... Range (inclusive and exclusive) ?: Ternary if-then-else = %= { /= -= += |= &= >>= <<= *= Assignment &&= ||= **= defined? Check if specified symbol defined not Logical negation or and Logical composition NOTE: Operators with a Yes in the method column are actually methods, and as such may be overridden.