D7net
Home
Console
Upload
information
Create File
Create Folder
About
Tools
:
/
opt
/
alt
/
ruby34
/
share
/
ri
/
system
/
syntax
/
Filename :
page-operators_rdoc.ri
back
Copy
U:RDoc::TopLevel[ i I"syntax/operators.rdoc:ETcRDoc::Parser::Simpleo:RDoc::Markup::Document:@parts[0S:RDoc::Markup::Heading: leveli: textI"Operators;To:RDoc::Markup::BlankLine o:RDoc::Markup::Paragraph;[I"UIn Ruby, operators such as <code>+</code>, are defined as methods on the class. ;TI"SLiterals[rdoc-ref:syntax/literals.rdoc] define their methods within the lower ;TI"2level, C language. String class, for example.;T@ o; ;[I"URuby objects can define or overload their own implementation for most operators.;T@ o; ;[I"Here is an example:;T@ o:RDoc::Markup::Verbatim;[ I"class Foo < String ;TI" def +(str) ;TI"3 self.concat(str).concat("another string") ;TI" end ;TI" end ;TI" ;TI"foobar = Foo.new("test ") ;TI"puts foobar + "baz " ;T:@format0o; ;[I"This prints:;T@ o;;[I"test baz another string ;T;0o; ;[I"IWhat operators are available is dependent on the implementing class.;T@ S; ; i;I"Operator Behavior;T@ o; ;[I"NHow a class behaves to a given operator is specific to that class, since ;TI"*operators are method implementations.;T@ o; ;[I"NWhen using an operator, it's the expression on the left-hand side of the ;TI"+operation that specifies the behavior.;T@ o;;[I"'a' * 3 #=> "aaa" ;TI"G3 * 'a' # TypeError: String can't be coerced into Integer ;T;0S; ; i;I"Logical Operators;T@ o; ;[I"@Logical operators are not methods, and therefore cannot be ;TI"?redefined/overloaded. They are tokenized at a lower level.;T@ o; ;[ I"HShort-circuit logical operators (<code>&&</code>, <code>||</code>, ;TI"U<code>and</code>, and <code>or</code>) do not always result in a boolean value. ;TI"SSimilar to blocks, it's the last evaluated expression that defines the result ;TI"of the operation.;T@ S; ; i;I"&<code>&&</code>, <code>and</code>;T@ o; ;[ I"`Both <code>&&</code>/<code>and</code> operators provide short-circuiting by executing each ;TI"Tside of the operator, left to right, and stopping at the first occurrence of a ;TI"Ofalsey expression. The expression that defines the result is the last one ;TI"Wexecuted, whether it be the final expression, or the first occurrence of a falsey ;TI"expression.;T@ o; ;[I"Some examples:;T@ o;;[I">true && 9 && "string" #=> "string" ;TI"9(1 + 2) && nil && "string" #=> nil ;TI";(a = 1) && (b = false) && (c = "string") #=> false ;TI" ;TI"7puts a #=> 1 ;TI";puts b #=> false ;TI"9puts c #=> nil ;T;0o; ;[I"KIn this last example, <code>c</code> was initialized, but not defined.;T@ S; ; i;I"%<code>||</code>, <code>or</code>;T@ o; ;[I"cThe means by which <code>||</code>/<code>or</code> short-circuits, is to return the result of ;TI")the first expression that is truthy.;T@ o; ;[I"Some examples:;T@ o;;[I"7(1 + 2) || true || "string" #=> 3 ;TI"=false || nil || "string" #=> "string";T;0: @file@:0@omit_headings_from_table_of_contents_below0